關於C#socket通訊,分爲同步和異步通訊,本文簡單介紹一下同步通訊。數組
通訊兩端分別爲客戶端(Client)和服務器(Server):服務器
(1)Cient:網絡
1:創建一個Socket對像;異步
2:用socket對像的Connect()方法以上面創建的EndPoint對像作爲參數,向服務器發出鏈接請求;socket
3:若是鏈接成功,就用socket對像的Send()方法向服務器發送信息;spa
4:用socket對像的Receive()方法接受服務器發來的信息 ;對象
5:通訊結束後必定記得關閉socket;blog
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Sockets; using System.Net; namespace Client { class Program { static Socket ClientSocket; static void Main(string[] args) { String IP = "127.0.0.1"; int port =8885 ; IPAddress ip = IPAddress.Parse(IP); //將IP地址字符串轉換成IPAddress實例 ClientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);//使用指定的地址簇協議、套接字類型和通訊協議 IPEndPoint endPoint = new IPEndPoint(ip, port); // 用指定的ip和端口號初始化IPEndPoint實例 ClientSocket.Connect(endPoint); //與遠程主機創建鏈接 Console.WriteLine("開始發送消息"); byte[] message = Encoding.ASCII.GetBytes("Connect the Server"); //通訊時實際發送的是字節數組,因此要將發送消息轉換字節 ClientSocket.Send(message); Console.WriteLine("發送消息爲:" + Encoding.ASCII.GetString(message)); byte[] receive = new byte[1024]; int length = ClientSocket.Receive(receive); // length 接收字節數組長度 Console.WriteLine("接收消息爲:" + Encoding.ASCII.GetString(receive)); ClientSocket.Close(); //關閉鏈接 } } }
客戶端返回結果:接口
(2)Server: ip
1:創建一個Socket對像;
2:用socket對像的Bind()方法綁定EndPoint;
3:用socket對像的Listen()方法開始監聽;
4:接受到客戶端的鏈接,用socket對像的Accept()方法建立新的socket對像用於和請求的客戶端進行通訊;
5:用新的socket對象接收(Receive)和發送(Send)消息。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Sockets; using System.Net; using System.Threading; namespace Server { class Program { static Socket ReceiveSocket; static void Main(string[] args) { int port = 8885; IPAddress ip = IPAddress.Any; // 偵聽全部網絡客戶接口的客活動 ReceiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//使用指定的地址簇協議、套接字類型和通訊協議
ReceiveSocket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReuseAddress,true); //有關套接字設置 IPEndPoint endPoint = new IPEndPoint(ip,port); ReceiveSocket.Bind(new IPEndPoint(ip, port)); //綁定IP地址和端口號 ReceiveSocket.Listen(10); //設定最多有10個排隊鏈接請求 Console.WriteLine("創建鏈接"); Socket socket = ReceiveSocket.Accept(); byte[] receive = new byte[1024]; socket.Receive(receive); Console.WriteLine("接收到消息:" + Encoding.ASCII.GetString(receive)); byte[] send = Encoding.ASCII.GetBytes("Success receive the message,send the back the message"); socket.Send(send); Console.WriteLine("發送消息爲:"+Encoding.ASCII.GetString(send)); } } }
服務器返回結果: