C#——Socket
最近公司让我搞个socket小程序(服务端)。
主要的功能:客户端发字符串到服务端,服务端接收后在界面上显示。
参照了网上许多代码,自己从中修改整理代码。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public Form4() { InitializeComponent(); this.Width = 1298; this.Height = 841; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.WindowState = FormWindowState.Maximized; System.Timers.Timer timer = new System.Timers.Timer(); timer.Enabled = true; timer.Interval = 60000;//执行间隔时间,单位为毫秒 timer.Start(); timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed); //设置IP和端口 SetServerIPAndPort(); } /// <summary> /// 根据当前程序目录的文本文件‘ServerIPAndPort.txt’内容来设定IP和端口 /// 格式:127.0.0.1:8885 /// </summary> private void SetServerIPAndPort() { try { FileStream fs = new FileStream("ServerIPAndPort.txt", FileMode.Open); StreamReader sr = new StreamReader(fs); string IPAndPort = sr.ReadLine(); ServerIP = IPAndPort.Split(':')[0]; //设定IP //ServerIP = GetLocalIPAddress();//设定IP port = int.Parse(IPAndPort.Split(':')[1]); //设定端口 Timer_out = int.Parse(IPAndPort.Split(':')[2]);//设定连接超时时间(毫秒) ipEnd = new IPEndPoint(IPAddress.Parse(ServerIP), port); //定义套接字类型 serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //连接 serverSocket.Bind(ipEnd); //开始侦听 serverSocket.Listen(10); //AddItemToListBox(string.Format("开始在{0}监听连接", ServerIP, port)); Thread myThread = new Thread(ListenClientConnect); myThread.Start(); sr.Close(); fs.Close(); } catch (Exception ex) { MessageBox.Show("配置IP与端口失败,错误原因:" + ex.Message); Application.Exit(); } } /// <summary> /// 监听客户端连接 /// </summary> private void ListenClientConnect() { Socket clientSocket = null; while (true) { try { clientSocket = serverSocket.Accept(); } catch { //当单击‘停止监听’或者退出此窗体时 AcceptTcpClient() 会产生异常 //因此可以利用此异常退出循环 break; } //clientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello")); Thread receiveThread = new Thread(ReceiveMessage); receiveThread.Start(clientSocket); } } /// <summary> /// 接收数据 /// </summary> /// <param name="socket"></param> /// <param name="timeout"></param> /// <returns></returns> private string Receive(Socket socket) { string result = string.Empty; //socket.ReceiveTimeout = Timer_out * 1000 * 60; List<byte> data = new List<byte>(); byte[] buffer = new byte[1024]; int length = 0; try { while ((length = socket.Receive(buffer)) > 0) { for (int j = 0; j < length; j++) { data.Add(buffer[j]); } if (length < buffer.Length) { break; } } } catch { } if (data.Count > 0) { result = Encoding.Default.GetString(data.ToArray(), 0, data.Count); } return result; } /// <summary> /// 接收消息 /// </summary> /// <param name="clientSocket"></param> private void ReceiveMessage(object clientSocket) { flg = true; myClientSocket = (Socket)clientSocket; byte[] result = new byte[1024]; while (flg) { try { //通过clientSocket接收数据 //int receiveNumber = myClientSocket.Receive(result,result.Length,0); //AddItemToListBox(Encoding.Unicode.GetString(result, 0, receiveNumber)); AddItemToListBox(Receive(myClientSocket)); flg = false; //break; } catch (Exception ex) { AddItemToListBox(ex.Message); myClientSocket.Shutdown(SocketShutdown.Both); myClientSocket.Close(); break; } } }