socket通常也稱作”套接字”,用於描述IP地址和端口,是一個通信鏈的句柄。應用程序通常通過”套接字”向網絡發出請求或者應答網絡請求。
這里構建一個簡單的例子,客戶端發消息,服務端接收,然后回執一條消息。大致能夠了解如何使用Socket進行通信。
服務端監聽,接收信息:
客戶端連接,並發送信息:
使用Socket通信,程序一般會在幕后運行,然后再合適的時間提示信息。這很自然的就會涉及到多線程的問題。在這個例子中因為每個連接都要創建一 個線程,所以需要對線程進行管理。這里我使用了兩個類:Connection(管理具體Socket連接)和SocketListener(管理線程和連 接)。
看看代碼吧:
1、Connection:服務端用於接收消息,處理具體的連接

1 public class Connection 2 { 3 Socket _connection; 4 5 public Connection(Socket socket) 6 { 7 _connection = socket; 8 } 9 10 public void WaitForSendData() 11 { 12 while (true) 13 { 14 byte[] bytes = new byte[1024]; 15 string data = ""; 16 17 //等待接收消息 18 int bytesRec = this._connection.Receive(bytes); 19 20 if (bytesRec == 0) 21 { 22 ReceiveText("客戶端[" + _connection.RemoteEndPoint.ToString() + "]連接關閉..."); 23 break; 24 } 25 26 data += Encoding.UTF8.GetString(bytes, 0, bytesRec); 27 ReceiveText("收到消息:" + data); 28 29 string sendStr = "服務端已經收到信息!"; 30 byte[] bs = Encoding.UTF8.GetBytes(sendStr); 31 _connection.Send(bs, bs.Length, 0); 32 } 33 } 34 35 public delegate void ReceiveTextHandler(string text); 36 public event ReceiveTextHandler ReceiveTextEvent; 37 private void ReceiveText(string text) 38 { 39 if (ReceiveTextEvent != null) 40 { 41 ReceiveTextEvent(text); 42 } 43 } 44 }
2、SocketListener:啟動服務端Socket監聽

1 public class SocketListener 2 { 3 public Hashtable Connection = new Hashtable(); 4 5 public void StartListen() 6 { 7 try 8 { 9 //端口號、IP地址 10 int port = 2000; 11 string host = "127.0.0.1"; 12 IPAddress ip = IPAddress.Parse(host); 13 IPEndPoint ipe = new IPEndPoint(ip, port); 14 15 //創建一個Socket類 16 Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 17 s.Bind(ipe);//綁定2000端口 18 s.Listen(0);//開始監聽 19 20 ReceiveText("啟動Socket監聽..."); 21 22 while (true) 23 { 24 Socket connectionSocket = s.Accept();//為新建連接創建新的Socket 25 26 ReceiveText("客戶端[" + connectionSocket.RemoteEndPoint.ToString() + "]連接已建立..."); 27 28 Connection gpsCn = new Connection(connectionSocket); 29 gpsCn.ReceiveTextEvent += new Connection.ReceiveTextHandler(ReceiveText); 30 31 Connection.Add(connectionSocket.RemoteEndPoint.ToString(), gpsCn); 32 33 //在新線程中啟動新的socket連接,每個socket等待,並保持連接 34 Thread thread = new Thread(new ThreadStart(gpsCn.WaitForSendData)); 35 thread.Name = connectionSocket.RemoteEndPoint.ToString(); 36 thread.Start(); 37 } 38 } 39 catch (ArgumentNullException ex1) 40 { 41 ReceiveText("ArgumentNullException:" + ex1); 42 } 43 catch (SocketException ex2) 44 { 45 ReceiveText("SocketException:" + ex2); 46 } 47 } 48 49 public delegate void ReceiveTextHandler(string text); 50 public event ReceiveTextHandler ReceiveTextEvent; 51 private void ReceiveText(string text) 52 { 53 if (ReceiveTextEvent != null) 54 { 55 ReceiveTextEvent(text); 56 } 57 } 58 }
3、服務端主程序

1 /// <summary> 2 /// Interaction logic for MainWindow.xaml 3 /// </summary> 4 public partial class MainWindow : Window 5 { 6 SocketListener listener; 7 public MainWindow() 8 { 9 InitializeComponent(); 10 11 InitServer(); 12 } 13 14 private void InitServer() 15 { 16 System.Timers.Timer t = new System.Timers.Timer(2000); 17 //實例化Timer類,設置間隔時間為5000毫秒; 18 t.Elapsed += new System.Timers.ElapsedEventHandler(CheckListen); 19 //到達時間的時候執行事件; 20 t.AutoReset = true; 21 t.Start(); 22 } 23 24 private void CheckListen(object sender, System.Timers.ElapsedEventArgs e) 25 { 26 if (listener != null && listener.Connection != null) 27 { 28 //label2.Content = listener.Connection.Count.ToString(); 29 ShowText("連接數:" + listener.Connection.Count.ToString()); 30 } 31 } 32 33 private void button1_Click(object sender, RoutedEventArgs e) 34 { 35 Thread th = new Thread(new ThreadStart(SocketListen)); 36 th.Start(); 37 } 38 39 private void SocketListen() 40 { 41 listener = new SocketListener(); 42 listener.ReceiveTextEvent += new SocketListener.ReceiveTextHandler(ShowText); 43 listener.StartListen(); 44 } 45 46 public delegate void ShowTextHandler(string text); 47 ShowTextHandler setText; 48 49 private void ShowText(string text) 50 { 51 if (System.Threading.Thread.CurrentThread != txtSocketInfo.Dispatcher.Thread) 52 { 53 if (setText == null) 54 { 55 setText = new ShowTextHandler(ShowText); 56 } 57 txtSocketInfo.Dispatcher.BeginInvoke(setText, DispatcherPriority.Normal, new string[] { text }); 58 } 59 else 60 { 61 txtSocketInfo.AppendText(text + "\n"); 62 } 63 } 64 65 private void button2_Click(object sender, RoutedEventArgs e) 66 { 67 ClientWindow client = new ClientWindow(); 68 client.Show(); 69 } 70 }
4、客戶端:建立連接,發送消息

4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 public partial class ClientWindow : Window { Socket c; public ClientWindow() { InitializeComponent(); InitClient(); } private void InitClient() { int port = 2000; string host = "127.0.0.1"; IPAddress ip = IPAddress.Parse(host); IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口轉化為IPEndPoint實例 c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//創建一個Socket ShowText("連接到Socket服務端..."); c.Connect(ipe);//連接到服務器 } private void button1_Click(object sender, RoutedEventArgs e) { try { ShowText("發送消息到服務端..."); string sendStr = textBox2.Text; byte[] bs = Encoding.ASCII.GetBytes(sendStr); c.Send(bs, bs.Length, 0); string recvStr = ""; byte[] recvBytes = new byte[1024]; int bytes; bytes = c.Receive(recvBytes, recvBytes.Length, 0);//從服務器端接受返回信息 recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes); ShowText("服務器返回信息:" + recvStr); } catch (ArgumentNullException ex1) { Console.WriteLine("ArgumentNullException:{0}", ex1); } catch (SocketException ex2) { Console.WriteLine("SocketException:{0}", ex2); } } private void ShowText(string text) { txtSockInfo.AppendText(text + "\n"); } }
這是一個WPF的程序,WPF對多線程訪問控件和WinForm的處理方式不太一樣。
轉自波斯馬,原文地址《C#通信之Socket通信的簡單例子》