c# TCP通訊(簡易伺服器)
阿新 • • 發佈:2018-12-13
網路中兩個主機用socket連線=.=
互動需要雙方相同的協議,伺服器的ip地址,伺服器程序需要port
客戶端咱們不管,給伺服器配置成接收所有ip與埠
所以
socket只需要指定協議,埠即可
沒有異常處理,沒有關閉,沒有人數限制,沒有面向物件
伺服器思路:
一個伺服器自身socket
- 指定協議
- 指定接收地址port
- 繫結地址與port
- 讓socket處於監聽狀態(引數別管,這只是個等待佇列長度,並不是寫了10就是隻接受10個客戶端請求(那麼怎麼寫呢,末尾給出程式碼)
- 獲取客戶端socket,開啟一個執行緒來處理資料(不然只接收一行)
- 想加雙工通訊就是在伺服器和客戶端各多開個執行緒,這裡少寫點程式碼,看起來舒服
服務端
using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; namespace Server01 { class Server01 { Socket serverSocket; public Server01() { serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint point = new IPEndPoint(IPAddress.Any, 9999); serverSocket.Bind(point); serverSocket.Listen(10); Console.WriteLine("伺服器啟動成功"); AccessToClient(); } public void AccessToClient() { Socket clientSocket = serverSocket.Accept(); Console.WriteLine("連線客戶端成功"); Thread clientThread = new Thread(AcceptClientData); clientThread.Start(clientSocket); AccessToClient(); } public void AcceptClientData(object obj) { Socket clientSocket = obj as Socket; Byte[] bytes = new Byte[1024]; //這裡客戶端斷開會異常 加try catch try { int length = clientSocket.Receive(bytes); //這裡length==0 不走 if (length > 0) { String str = Encoding.UTF8.GetString(bytes, 0, length); Console.WriteLine("o((>ω< ))o:" + str); AcceptClientData(obj); } } catch { Console.WriteLine("客戶端斷開"); } } } class Program { static void Main(string[] args) { Server01 server = new Server01(); } } }
客戶端思路:
- 也就是伺服器的開頭,建立socket
- 配置ip port
- 這一步不要繫結,直接連線就行
- 這裡連線伺服器寫了個傳送資料,可以自測
- 要接收伺服器資訊,多開個執行緒就行相信你可以的=.=
客戶端
using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; namespace Client01 { class Client01 { Socket clientSocket; public Client01() { clientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp); IPEndPoint point = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999); Console.WriteLine("客戶端啟動成功"); clientSocket.Connect(point); AccessToServer(); } void AccessToServer() { SendMessageToServer(); } void SendMessageToServer() { while (true) { String str = Console.ReadLine(); clientSocket.Send(Encoding.UTF8.GetBytes(str)); } } } class Program { static void Main(string[] args) { Client01 client = new Client01(); } } }