This article is a mirror article of machine translation, please click here to jump to the original article.

View: 34213|Reply: 2

[Source] C# implements Socket communication client code

[Copy link]
Posted on 12/23/2015 2:51:34 PM | | |
  1. public static string socketToClient(string ip, int port, string msg)
  2.         {
  3.             //将网络端点表示为IP地址和端口 用于socket侦听时绑定  
  4.             IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(ip), port); //填写自己电脑的IP或者其他电脑的IP,如果是其他电脑IP的话需将ConsoleApplication_socketServer工程放在对应的电脑上。
  5.             Socket clientSocket = new Socket(ipep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  6.             //将Socket连接到服务器  
  7.             try
  8.             {
  9.                 clientSocket.Connect(ipep);
  10.                 String outBufferStr;
  11.                 Byte[] outBuffer = new Byte[1024];
  12.                 Byte[] inBuffer = new Byte[1024];
  13.                 while (true)
  14.                 {
  15.                     //发送消息  
  16.                     outBufferStr = msg;
  17.                     outBuffer = Encoding.ASCII.GetBytes(outBufferStr);
  18.                     clientSocket.Send(outBuffer, outBuffer.Length, SocketFlags.None);

  19.                     //接收服务器端信息        
  20.                     clientSocket.Receive(inBuffer, 1024, SocketFlags.None);//如果接收的消息为空 阻塞 当前循环
  21.                     Console.WriteLine("服务器说:");
  22.                     Console.WriteLine(Encoding.ASCII.GetString(inBuffer));
  23.                     return Encoding.ASCII.GetString(inBuffer);
  24.                 }
  25.             }
  26.             catch
  27.             {
  28.                 return null;
  29.             }
  30.         }
Copy code






Previous:SMS4 algorithm, just understood and written, the next step is to prepare the SM3 hash algorithm
Next:Use JS to automatically change the background image of the homepage
Posted on 3/26/2022 4:01:04 PM |
Code code code
Posted on 6/25/2024 11:11:52 PM |

Code code code
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com