VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > c#编程 >
  • C#教程之c# socket编程udp客户端实现代码分享

代码如下:

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();

相关教程