本身琢磨Socket剛剛幾天,因此整理出來和你們共享一下。廢話少說直接進入正題。數組
在C#中提供了兩種網絡服務,一種是Socket類,另外一種是TcpListener(服務器),TcpClient(客戶端);緩存
至於這兩種有什麼區別那;MSDN上是這樣解釋的:服務器
TcpClient 類,TcpListener 類提供了一些簡單的方法,用於在同步阻止模式下經過網絡來鏈接、發送和接收流數據。網絡
Socket 類爲網絡通訊提供了一套豐富的方法和屬性。 Socket 類容許您使用 ProtocolType 枚舉中所列出的任何一種協議執行異步和同步數據傳輸。併發
我的理解就是一個是用於簡單的業務,一種用於複雜的業務。因此感受是同樣的。本文事例主要用Socket類來實現。通常來講複雜的會了,簡單的應該也差很少了。異步
先從第一個情景來講:第一個就是創建多人聊天的模式,就是多個客戶端鏈接一個服務器,而後能夠和多個客戶端通訊。就像QQ裏的羣聊。socket
首先咱們來見一個服務器:this
就包含一個文本框就好了,裏邊具體代碼以下:spa
1 public partial class server : Form 2 { 3 private IPEndPoint ServerInfo;//存放服務器的IP和端口信息 4 private Socket ServerSocket;//服務端運行的SOCKET 5 private Thread ServerThread;//服務端運行的線程 6 private Socket[] ClientSocket;//爲客戶端創建的SOCKET鏈接 7 private int ClientNumb;//存放客戶端數量 8 private byte[] MsgBuffer;//存放消息數據 9 10 private object obj; 11 12 public server() 13 { 14 InitializeComponent(); 15 ListenClient(); 16 } 17 18 /// <summary> 19 /// 開始服務,監聽客戶端 20 /// </summary> 21 private void ListenClient() 22 { 23 try 24 { 25 ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 26 IPAddress ip = IPAddress.Parse("127.0.0.1"); 27 ServerInfo = new IPEndPoint(ip, Int32.Parse("3000")); 28 ServerSocket.Bind(ServerInfo); 29 ServerSocket.Listen(10); 30 31 ClientSocket = new Socket[65535]; 32 MsgBuffer = new byte[65535]; 33 ClientNumb = 0; 34 35 ServerThread = new Thread(new ThreadStart(RecieveAccept)); 36 ServerThread.Start(); 37 } 38 catch (System.Exception ex) 39 { 40 41 } 42 } 43 44 /// <summary> 45 /// 添加阻塞,監聽客戶端 46 /// </summary> 47 private void RecieveAccept() 48 { 49 while (true) 50 { 51 //等待接受客戶端鏈接,若是有就執行下邊代碼,沒有就阻塞 52 ClientSocket[ClientNumb] = ServerSocket.Accept(); 53 //接受客戶端信息,沒有阻塞,則會執行下邊輸出的代碼;若是是Receive則不會執行下邊輸出代碼 54 ClientSocket[ClientNumb].BeginReceive(MsgBuffer, 0, MsgBuffer.Length, SocketFlags.None, 55 new AsyncCallback(ReceiveCallback), ClientSocket[ClientNumb]); 56 this.Invoke((MethodInvoker)delegate 57 { 58 lock (this.textBox1) 59 this.textBox1.Text += "客戶端:" + ClientNumb.ToString() + "鏈接成功!" + "\r\n"; 60 }); 61 ClientNumb++; 62 } 63 } 64 65 /// <summary> 66 /// 回發數據到客戶端 67 /// </summary> 68 /// <param name="ar"></param> 69 private void ReceiveCallback(IAsyncResult ar) 70 { 71 try 72 { 73 Socket rSocket = (Socket)ar.AsyncState; 74 int rEnd = rSocket.EndReceive(ar); 75 76 for (int i = 0; i < ClientNumb; i++) 77 { 78 if (ClientSocket[i].Connected) 79 { 80 //發送數據到客戶端 81 ClientSocket[i].Send(MsgBuffer, 0, rEnd, SocketFlags.None); 82 } 83 84 //同時接受客戶端回發的數據,用於回發 85 rSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(ReceiveCallback), rSocket); 86 } 87 } 88 catch (System.Exception ex) 89 { 90 91 } 92 } 93 }
而後咱們添加客戶端代碼,客戶端要一個按鈕和兩個文本框.net
具體代碼以下:
1 public partial class Client : Form 2 { 3 private IPEndPoint ServerInfo; 4 private Socket ClientSocket; 5 private object obj; 6 7 //信息接收緩存 8 private Byte[] MsgBuffer; 9 //信息發送存儲 10 private Byte[] MsgSend; 11 12 public Client() 13 { 14 InitializeComponent(); 15 ConnectServer(); 16 this.button1.Click += new EventHandler(button1_Click); 17 } 18 19 /// <summary> 20 /// 打開客戶端,即鏈接服務器 21 /// </summary> 22 private void ConnectServer() 23 { 24 try 25 { 26 ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 27 MsgBuffer = new byte[65535]; 28 MsgSend = new byte[65535]; 29 IPAddress ip = IPAddress.Parse("127.0.0.1"); 30 ServerInfo = new IPEndPoint(ip, Int32.Parse("3000")); 31 ClientSocket.Connect(ServerInfo); 32 //發送信息至服務器 33 ClientSocket.Send(Encoding.Unicode.GetBytes("用戶: 進入系統!" + "\r\n")); 34 ClientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, SocketFlags.None, 35 new AsyncCallback(ReceiveCallback), null); 36 this.textBox1.Text += "登陸服務器成功" + "\r\n"; 37 } 38 catch (System.Exception ex) 39 { 40 41 } 42 } 43 44 /// <summary> 45 /// 回調時調用 46 /// </summary> 47 /// <param name="ar"></param> 48 private void ReceiveCallback(IAsyncResult ar) 49 { 50 int rEnd = ClientSocket.EndReceive(ar); 51 this.Invoke((MethodInvoker)delegate 52 { 53 lock (this.textBox1) 54 { 55 this.textBox1.Text += Encoding.Unicode.GetString(MsgBuffer, 0, rEnd) + "\r\n"; 56 } 57 }); 58 ClientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(ReceiveCallback), null); 59 } 60 61 /// <summary> 62 /// 發送信息 63 /// </summary> 64 /// <param name="sender"></param> 65 /// <param name="e"></param> 66 private void button1_Click(object sender, EventArgs e) 67 { 68 MsgSend = Encoding.Unicode.GetBytes("說:\n" + this.textBox2.Text + "\n\r"); 69 if (ClientSocket.Connected) 70 { 71 ClientSocket.Send(MsgSend); 72 } 73 } 74 75 } 76 }
這樣先運行服務器,在多運行幾個客戶端就能夠了。
下邊講一下第二種案例:這種是多個客戶端和服務器鏈接,每一個客戶端均可以和服務器通訊,可是客戶端之間沒有通訊,並且每一個客戶端和服務器通訊時,不會影響其餘客戶端。
具體樣式如圖:
接着咱們來看看具體的代碼:
先來看看服務器的,樣式和第一種同樣,
具體代碼:
1 public partial class Server : Form 2 { 3 private Socket socket = null; 4 private Thread thread = null; 5 6 public Server() 7 { 8 InitializeComponent(); 9 StartListening(); 10 } 11 12 /// 13 /// 開始監聽客戶端 14 /// 15 private void StartListening() 16 { 17 try 18 { 19 socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 20 IPAddress ipaddress = IPAddress.Parse("127.0.0.1"); 21 IPEndPoint endPoint = new IPEndPoint(ipaddress, int.Parse("3000")); 22 23 socket.Bind(endPoint); 24 socket.Listen(20); 25 26 thread = new Thread(new ThreadStart(WatchConnection)); 27 thread.IsBackground = true; 28 thread.Start(); 29 30 this.listBox1.Text = "開始監聽客戶端傳來的消息" + "\r\n"; 31 } 32 catch (System.Exception ex) 33 { 34 this.listBox1.Text += "SocketException" + ex; 35 } 36 } 37 38 Socket[] socConnection = new Socket[12]; 39 private static int clientNum = 0; 40 41 /// <summary> 42 /// 監聽客戶端發來的請求 43 /// </summary> 44 private void WatchConnection() 45 { 46 while (true) 47 { 48 socConnection[clientNum] = socket.Accept(); 49 this.Invoke((MethodInvoker)delegate 50 { 51 this.listBox1.Text += "客戶端鏈接成功" + "\r\n"; 52 }); 53 54 Thread thread = new Thread(new ParameterizedThreadStart(ServerRecMsg)); 55 thread.IsBackground = true; 56 thread.Start(socConnection[clientNum]); 57 clientNum++; 58 } 59 } 60 61 /// <summary> 62 /// 接受客戶端消息併發送消息 63 /// </summary> 64 /// <param name="socketClientPara"></param> 65 private void ServerRecMsg(object socketClientPara) 66 { 67 Socket socketServer = socketClientPara as Socket; 68 try 69 { 70 while (true) 71 { 72 byte[] arrServerRecMsg = new byte[1024 * 1024]; 73 int length = socketServer.Receive(arrServerRecMsg); 74 75 string strSRecMsg = Encoding.UTF8.GetString(arrServerRecMsg, 0, length); 76 this.Invoke((MethodInvoker)delegate 77 { 78 this.listBox1.Text += "接收到:" + strSRecMsg + "\r\n"; 79 }); 80 81 byte[] arrSendMsg = Encoding.UTF8.GetBytes("收到服務器發來的消息"); 82 //發送消息到客戶端 83 socketServer.Send(arrSendMsg); 84 } 85 } 86 catch (System.Exception ex) 87 { 88 89 } 90 } 91 }
再來看看客戶端代碼:
樣式和第一種也同樣:
1 public partial class Client : Form 2 { 3 private Socket socketClient = null; 4 private Thread threadClient = null; 5 6 public Client() 7 { 8 InitializeComponent(); 9 ConnectionServer(); 10 this.button1.Click += new EventHandler(button1_Click); 11 } 12 13 /// <summary> 14 /// 鏈接服務器 15 /// </summary> 16 private void ConnectionServer() 17 { 18 socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 19 IPAddress ipaddress = IPAddress.Parse("127.0.0.1"); 20 IPEndPoint endPoint = new IPEndPoint(ipaddress, int.Parse("3000")); 21 try 22 { 23 socketClient.Connect(endPoint); 24 threadClient = new Thread(RecMsg); 25 threadClient.IsBackground = true; 26 threadClient.Start(); 27 } 28 catch (System.Exception ex) 29 { 30 31 } 32 33 } 34 35 /// <summary> 36 /// 接收服務器消息 37 /// </summary> 38 private void RecMsg() 39 { 40 while (true) 41 { 42 //內存緩衝區1M,用於臨時存儲接收到服務器端的消息 43 byte[] arrRecMsg = new byte[1024 * 1024]; 44 //將接收到的數據放入內存緩衝區,獲取其長度 45 int length = socketClient.Receive(arrRecMsg); 46 //將套接字獲取到的字節數組轉換爲咱們能夠理解的字符串 47 string strRecMsg = Encoding.UTF8.GetString(arrRecMsg, 0, length); 48 this.Invoke((MethodInvoker)delegate 49 { 50 lock (this.listBox1) 51 { 52 this.listBox1.Text += "服務器:" + strRecMsg + "\r\n"; 53 } 54 }); 55 } 56 } 57 58 /// <summary> 59 /// 向服務器發送消息 60 /// </summary> 61 /// <param name="sender"></param> 62 /// <param name="e"></param> 63 private void button1_Click(object sender, EventArgs e) 64 { 65 ClientSendMsg(this.textBox1.Text.Trim()); 66 } 67 68 /// <summary> 69 /// 發送信息到服務器 70 /// </summary> 71 /// <param name="sendMsg"></param> 72 private void ClientSendMsg(string sendMsg) 73 { 74 //將輸入的字符串轉化爲機器能夠識別的字節數組 75 byte[] arrClientSendMsg = Encoding.UTF8.GetBytes(sendMsg); 76 //發送數據 77 socketClient.Send(arrClientSendMsg); 78 this.listBox1.Text += "客戶端:" + sendMsg + "\r\n"; 79 } 80 }
到此兩種方式就說完了,不知道說的對不對,請各位吐槽!!!,轉載註明出處。