標籤:style blog http color 2014 os
好久沒有寫CS端代碼,今天有空複習一下SOCKET。
功能說明:
1、服務端向用戶端發送資訊
2、用戶端向服務端發送資訊
效果如:
服務端代碼:
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint localPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5000); serverSocket.Bind(localPoint); serverSocket.Listen(10); new Thread(s => { while (true) { Socket clientSocket = ((Socket)s).Accept(); clientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello")); clients.Add(clientSocket); new Thread((cS) => { Socket myClientSocket = (Socket)clientSocket; while (true) { try { byte[] result = new byte[1024 * 1024]; int receiveNumber = myClientSocket.Receive(result); string realMsg = string.Format("接收用戶端{0}訊息{1}\r\n", myClientSocket.RemoteEndPoint.ToString(), Encoding.Default.GetString(result, 0, receiveNumber)); if (label1.InvokeRequired) { label1.BeginInvoke(new Action<string>((msg) => { label1.Text += msg; }), realMsg); } } catch (Exception ex) { if (myClientSocket != null && myClientSocket.Connected) { myClientSocket.Shutdown(SocketShutdown.Both); myClientSocket.Close(); } } } }) { IsBackground = true }.Start(clientSocket); } }) { IsBackground = true }.Start(serverSocket);
用戶端代碼:
try { socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect("127.0.0.1", 5000); new Thread((s) => { Socket cS = (Socket)s; while (true) { byte[] byteMsg = new byte[1024 * 1024]; int realResult = cS.Receive(byteMsg); string msg = Encoding.Default.GetString(byteMsg, 0, realResult); if (label1.InvokeRequired) { Action<string> a = (rm) => { this.label1.Text += rm + "\r\n"; }; label1.BeginInvoke(a, msg); } } }) { IsBackground = true }.Start(socket); button1.Enabled = false; } catch (Exception ex) { button1.Enabled = true; }