Socket,这玩意,当时不会的时候,抄别人的都用不好,简单的一句话形容就是“笨死了”;也是很多人写的太复杂,不容易理解造成的。最近在搞erlang和C的通讯,也想试试erlang是不是可以和C#简单通讯,就简单的做了些测试用例,比较简单,觉得新手也可以接受。
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Windows.Forms; 9 using System.Net.Sockets; 10 using System.Net; 11 using System.Threading; 12 13 namespace ChatClient 14 { 15 public partial class Form1 : Form 16 { 17 private System.Windows.Forms.RichTextBox richTextBox1; 18 private System.Windows.Forms.TextBox textBox1; 19 private System.ComponentModel.IContainer components = null; 20 21 /// <summary> 22 /// 服务端侦听端口 23 /// </summary> 24 private const int _serverPort = 8707; 25 /// <summary> 26 /// 客户端侦听端口 27 /// </summary> 28 private const int _clientPort = 8708; 29 /// <summary> 30 /// 缓存大小 31 /// </summary> 32 private const int _bufferSize = 1024; 33 /// <summary> 34 /// 服务器IP 35 /// </summary> 36 private const string ServerIP = "172.17.47.199"; //手动修改为指定服务器ip 37 38 private Thread thread; 39 40 private void Form1_Load(object sender, EventArgs e) 41 { 42 thread = new Thread(new ThreadStart(delegate { Listenning(); })); 43 thread.Start(); 44 } 45 46 void textBox_KeyUp(object sender, KeyEventArgs e) 47 { 48 if (e.KeyCode == Keys.Enter) 49 { 50 string msg; 51 if ((msg = textBox1.Text.Trim()).Length > 0) 52 { 53 SendMessage(msg); 54 } 55 textBox1.Clear(); 56 } 57 } 58 59 void SendMessage(string msg) 60 { 61 try 62 { 63 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 64 IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ServerIP), _serverPort); 65 socket.Connect(endPoint); 66 byte[] buffer = System.Text.ASCIIEncoding.UTF8.GetBytes(msg); 67 socket.Send(buffer); 68 socket.Close(); 69 } 70 catch 71 { } 72 } 73 74 void Listenning() 75 { 76 TcpListener listener = new TcpListener(_clientPort); 77 listener.Start(); 78 while (true) 79 { 80 Socket socket = listener.AcceptSocket(); 81 byte[] buffer = new byte[_bufferSize]; 82 socket.Receive(buffer); 83 int lastNullIndex = _bufferSize - 1; 84 while (true) 85 { 86 if (buffer[lastNullIndex] != '