亲宝软件园·资讯

展开

c# socket编程 c# socket编程udp客户端实现代码分享

人气:0
想了解c# socket编程udp客户端实现代码讲解的相关内容吗,在本文为您仔细讲解c# socket编程的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:socket编程udp,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();

加载全部内容

相关教程
猜你喜欢
用户评论