cēsocketプログラミングupクライアント実現コード共有



Console.WriteLine("This is a Client, host name is {0}", Dns.GetHostName());
//
IPEndPoint ipe = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8001);
// , ,
Socket ConnSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
string welcome = "Client Message:Hello!!!";
byte[] data = new byte[1024];
data = Encoding.ASCII.GetBytes(welcome);
//
ConnSocket.SendTo(data, data.Length, SocketFlags.None, ipe);
IPEndPoint server = new IPEndPoint(IPAddress.Any, 0);
//
EndPoint Remote = (EndPoint)server;
data = new byte[1024];
// IP , ,
//server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 100);
int recv = ConnSocket.ReceiveFrom(data, ref Remote);
//
Console.WriteLine("Message received from {0}: ", Remote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
while (true) //
{
    string input = Console.ReadLine();
    if (input == "exit") //
    {
        ConnSocket.SendTo(Encoding.ASCII.GetBytes(input), Remote);
        data = new byte[1024];
        recv = ConnSocket.ReceiveFrom(data, ref Remote);
        Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
        break;
    }
    else
    {
        ConnSocket.SendTo(Encoding.ASCII.GetBytes("Client Message:" + input), Remote);
        data = new byte[1024];
        recv = ConnSocket.ReceiveFrom(data, ref Remote);
        Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
    }
}
Console.WriteLine("Stopping Client.");
ConnSocket.Close();