Friday, April 3, 2015

C# UDP Server/Client 예제

//Server
System.Net.Sockets.UdpClient udpClient = new System.Net.Sockets.UdpClient("127.0.0.1", 5555);
String cmd = "dump";
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] dgrams = encoding.GetBytes(cmd);
udpClient.Send(dgrams, dgrams.Length);
udpClient.Close();

//Client
static private UdpClient udpServer;
static private byte[] data;
static private IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 5555);
static private IPEndPoint server = new IPEndPoint(IPAddress.Any, 0);
static private void ThreadProc()
{
    while (true)
    {
        data = udpServer.Receive(ref server);
        string s = Encoding.Default.GetString(data);
        Console.WriteLine(s);
    }
}
private void Form1_Load(object sender, EventArgs e)
{
    ipep = new IPEndPoint(IPAddress.Any, 5555);
    server = new IPEndPoint(IPAddress.Any, 0);
    udpServer = new UdpClient(ipep);
    data = new byte[1024];
    Thread thread = new Thread(new ThreadStart(ThreadProc));
    thread.Start();
    Console.WriteLine("Thread started");
}


No comments:

Post a Comment