当前位置:   article > 正文

C# Socket UDP 通信_c# socket udp接收

c# socket udp接收

UDP是无连接不安全的通信,但效率高,通常用在视频或语音通话等方面,要求高效率的传输,代码如下:

代码运行平台 Visual Studio 2019

服务端代码:

  1. /*******
  2. *
  3. * UDP通讯:服务器端
  4. * 和TCP不一样的地方:
  5. * 1、不需要Listen()和Accept()了
  6. * 2、UDP中用的是_SocketServer.ReceiveFrom(),而不是_SocketServer.Receive()
  7. *
  8. * *******/
  9. using System;
  10. using System.Threading;
  11. using System.Net;
  12. using System.Net.Sockets;
  13. using System.Text;
  14. namespace SocketServer_UDP
  15. {
  16. class Server
  17. {
  18. private Socket _SocketServer; //套接字
  19. private bool _IsListenConnection = true; //是否在监听(目的是方便退出)
  20. private IPEndPoint endPoint;
  21. public Server()
  22. {
  23. //定义网络终节点(封装IP与端口)
  24. endPoint = new IPEndPoint(IPAddress.Parse("192.168.1.8"), 8080);
  25. //实例化套接字(监听)
  26. _SocketServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  27. //服务器端绑定地址
  28. _SocketServer.Bind(endPoint);
  29. Console.WriteLine("服务端已启动...");
  30. Thread thSend = new Thread(SendMsg);
  31. thSend.Start();
  32. //这里必须另起一个线程,因为接收收时线程是卡着等待着的
  33. Thread thReceive = new Thread(ReceiveMsg);
  34. thReceive.Start();
  35. }
  36. /// <summary>
  37. /// 接受客户端消息
  38. /// </summary>
  39. private void ReceiveMsg()
  40. {
  41. EndPoint ep = new IPEndPoint(IPAddress.Any,0); //Any代表任何客户端,0代表任何端口
  42. while (true)
  43. {
  44. //准备一个“数据缓存”
  45. byte[] msgArray = new byte[1024 * 1024]; //一个1M的空间
  46. //接收客户端发来的消息,返回数据的真实长度
  47. int trueClientMsgLength = _SocketServer.ReceiveFrom(msgArray, ref ep); //这里和TCP连接不一样了,用的是ReceiveForm()而不是Receive()????
  48. //byte字节数组转string
  49. string strMsg = Encoding.UTF8.GetString(msgArray, 0, trueClientMsgLength);
  50. Console.WriteLine("客户端发来的数据: " + strMsg);
  51. }
  52. }
  53. /// <summary>
  54. /// 向指定客户端发送消息
  55. /// </summary>
  56. private void SendMsg()
  57. {
  58. //EndPoint ep = (EndPoint)endPoint;
  59. while (true)
  60. {
  61. EndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.1.8"), 8081);
  62. string snedMsg = Console.ReadLine(); //输入要发送的内容
  63. byte[] byteMsg = Encoding.UTF8.GetBytes(snedMsg);
  64. _SocketServer.SendTo(byteMsg, ep);
  65. }
  66. }
  67. static void Main(string[] args)
  68. {
  69. Server server = new Server();
  70. }
  71. }
  72. }

客户端代码:

  1. /************
  2. *
  3. * UDP端通信:客户端
  4. * 和TCP不一致的地方:
  5. * 1、UDP发送用的是SendTo(),而TCP用的是Send()
  6. *
  7. * ************/
  8. using System;
  9. using System.Threading;
  10. using System.Net;
  11. using System.Net.Sockets;
  12. using System.Text;
  13. namespace SocketClient_UDP
  14. {
  15. class Client
  16. {
  17. private Socket _SocketClient; //客户端通讯套接字
  18. private IPEndPoint serverEndPoint; //连接到的服务器IP与端口信息
  19. public Client()
  20. {
  21. //(服务器端)通讯地址与端口号
  22. serverEndPoint = new IPEndPoint(IPAddress.Parse("192.168.1.8"), 8081);
  23. //建立客户端的Socket
  24. _SocketClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  25. //绑定
  26. _SocketClient.Bind(serverEndPoint);
  27. //另起一个发送线程
  28. Thread thSendMsg = new Thread(SendMsg);
  29. thSendMsg.Start();
  30. //这里必须另起一个线程,接收时线程是卡着等待消息接收的
  31. Thread thReceive = new Thread(ReceiveMsg);
  32. thReceive.Start();
  33. }
  34. /// <summary>
  35. /// 向服务端发送消息
  36. /// </summary>
  37. private void SendMsg()
  38. {
  39. try
  40. {
  41. EndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.1.8"),8080);
  42. while (true)
  43. {
  44. //输入信息
  45. string strMsg = Console.ReadLine();
  46. //string转化为字节数组
  47. byte[] byteArray = Encoding.UTF8.GetBytes(strMsg);
  48. //发送数据
  49. _SocketClient.SendTo(byteArray, ep); //这里和TCP不一致,TCP用的是Send()
  50. Console.WriteLine("我: " + strMsg);
  51. }
  52. }
  53. catch (Exception)
  54. {
  55. //关闭前端和后端连接
  56. _SocketClient.Shutdown(SocketShutdown.Both);
  57. //清理连接的资源
  58. _SocketClient.Close();
  59. }
  60. }
  61. /// <summary>
  62. /// 接收服务端发送的消息
  63. /// </summary>
  64. private void ReceiveMsg()
  65. {
  66. try
  67. {
  68. EndPoint ep = (EndPoint)new IPEndPoint(IPAddress.Any, 0);
  69. while (true)
  70. {
  71. byte[] bytes = new byte[1024 * 1024]; //定义一个1M的数据缓存空间
  72. int trueClientMsgLength = _SocketClient.ReceiveFrom(bytes, ref ep); //真正接收到的数据长度
  73. string strMsg= Encoding.UTF8.GetString(bytes, 0, trueClientMsgLength);
  74. Console.WriteLine("服务端: " + strMsg);
  75. }
  76. }
  77. catch (Exception)
  78. {
  79. throw;
  80. }
  81. }
  82. static void Main(string[] args)
  83. {
  84. Client obj = new Client();
  85. }
  86. }
  87. }

大家修改各自的IP地址后,此代码即可运行

运行结果如下:

下一节进行TCP通信的讲解....... 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/895529
推荐阅读
相关标签
  

闽ICP备14008679号