開発環境 Microsoft Visual C++ 2010 Express (SP1)
実行環境 Microsoft Windows XP Home Edition (SP3)
プロジェクトの種類 空の CLR プロジェクト
プロジェクト名 ClrServer
プロジェクト名 ClrClient

ClrServer.cpp
#pragma comment(linker, "/subsystem:windows /entry:main")
 
// .NET参照
#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>
 
// 名前空間
using namespace System;
using namespace System::Drawing;
using namespace System::Net;
using namespace System::Net::Sockets;
using namespace System::Text;
using namespace System::Windows::Forms;
 
ref class Form1 : Form
{
public:
	Form1(void)
	{
		InitializeCompnent();
 
		ep = gcnew IPEndPoint(IPAddress::Any, 8080);
		udp = gcnew UdpClient(ep);
		udp->BeginReceive(gcnew AsyncCallback(this, &Form1::RecvCallback), nullptr);
	}
 
	~Form1()
	{
		udp->Close();
	}
private:
	TextBox^ msg;
	IPEndPoint^ ep;
	UdpClient^ udp;
 
	void InitializeCompnent(void)
	{
		msg = gcnew TextBox;
		SuspendLayout();
 
		// msg
		msg->Bounds = Rectangle(10, 10, 300, 60);
		msg->Multiline = true;
		msg->ScrollBars = ScrollBars::Vertical;
 
		// Form1
		ClientSize = Drawing::Size(320, 120);
		Controls->Add(msg);
		Text = L"ClrServer";
 
		ResumeLayout(false);
		PerformLayout();
	}
 
	void RecvCallback(System::IAsyncResult^ ar)
	{
		array<Byte>^ dgram = udp->EndReceive(ar, ep);
		String^ str = Encoding::Unicode->GetString(dgram);
		msg->Invoke(gcnew D_SetMsg(this, &Form1::SetMsg), str);
		udp->BeginReceive(gcnew AsyncCallback(this, &Form1::RecvCallback), nullptr);
	}
 
	delegate void D_SetMsg(String^ str);
	void SetMsg(String^ str)
	{
		msg->Text = str;
	}
};
 
[STAThread]
int main()
{
	Application::Run(gcnew Form1);
	return 0;
}
 

ClrClient.cpp
#pragma comment(linker, "/subsystem:windows /entry:main")
 
// .NET参照
#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>
 
// 名前空間
using namespace System;
using namespace System::Drawing;
using namespace System::Net::Sockets;
using namespace System::Text;
using namespace System::Windows::Forms;
 
ref class Form1 : Form
{
public:
	Form1(void)
	{
		InitializeCompnent();
	}
private:
	TextBox^ msg;
	Button^ send;
 
	void InitializeCompnent(void)
	{
		msg = gcnew TextBox;
		send = gcnew Button;
		SuspendLayout();
 
		// msg
		msg->Bounds = Rectangle(10, 10, 300, 60);
		msg->Multiline = true;
		msg->ScrollBars = ScrollBars::Vertical;
 
		// send
		send->Text = L"送信";
		send->Location = Point(10, 80);
		send->Click += gcnew EventHandler(this, &Form1::SendClick);
 
		// Form1
		ClientSize = Drawing::Size(320, 120);
		Controls->Add(msg);
		Controls->Add(send);
		Text = L"ClrClient";
 
		ResumeLayout(false);
		PerformLayout();
	}
private:
	void SendClick(Object^ sender, EventArgs^ e)
	{
		UdpClient^ udp = gcnew UdpClient;
		array<Byte>^ dgram = Encoding::Unicode->GetBytes(msg->Text);
		udp->Send(dgram, dgram->Length, L"localhost", 8080);
		udp->Close();
	}
};
 
[STAThread]
int main()
{
	Application::Run(gcnew Form1);
	return 0;
}
 
最終更新:2012年10月11日 20:30