欢迎来到山村网

c# socket编程实现udp客户端

2019-03-02 10:58:59浏览:782 来源:山村网   
核心摘要:这篇文章主要介绍了c# socket编程实现udp客户端,大家参考使用吧代码如下:Console.WriteLine(This is a Client, host name is {0

这篇文章主要介绍了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();
(责任编辑:豆豆)
下一篇:

C# Socket连接请求超时机制实现代码分享

上一篇:

c#异步读取数据库与异步更新ui的代码实现

  • 信息二维码

    手机看新闻

  • 分享到
打赏
免责声明
• 
本文仅代表作者个人观点,本站未对其内容进行核实,请读者仅做参考,如若文中涉及有违公德、触犯法律的内容,一经发现,立即删除,作者需自行承担相应责任。涉及到版权或其他问题,请及时联系我们 xfptx@outlook.com