Socket(套接字)編程(Tcp)
1.基於Tcp協議的Socket通訊類似於B/S架構,面向連接,但不同的是服務器端可以向客戶端 主動推送消息。
使用Tcp協議通訊需要具備以下幾個條件:
(1).建立一個套接字(Socket)
(2).綁定服務器端IP地址及端口號--服務器端
(3).利用Listen()方法開啟監聽--服務器端
(4).利用Accept()方法嘗試與客戶端建立一個連接--服務器端
(5).利用Connect()方法與服務器建立連接--客戶端
(6).利用Send()方法向建立連接的主機發送消息
(7).利用Receive()方法接受來自建立連接的主機的消息(可靠連接)
服務器端:
1 using System; 2 using System.Net; 3 using System.Net.Sockets; 4 using System.Text; 5 6 namespace TCP服務器端TcpServer 7 { 8 internal class Program 9 { 10 static void Main(string[] args) 11 { 12 //Console.WriteLine("Hello World!"); 13 //1234 14 // IP 192.168.1.145 Port端口號 內網=局域網 外網 15 //網絡地址 16 //城市 路 小區 單元 xx 小明收 17 //城市 路 小區 單元 xx 18 // xx樓 x單元 xx 19 Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 20 21 IPAddress ipAddress = new IPAddress(new byte[] { 192, 168, 1, 184 }); 22 // IP + Port 23 IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 6688); 24 //綁定ipEndPoint 25 tcpServer.Bind(ipEndPoint); 26 //最大連接數 27 tcpServer.Listen(100); 28 29 Console.WriteLine("開始接客了 ..."); 30 //等待客戶端連接 31 Socket client = tcpServer.Accept(); 32 Console.WriteLine("一個客戶端鏈接過來了"); 33 //分配1024個字節大小的內存給data 34 byte[] data = new byte[1024]; 35 //接收客戶端消息 36 int length = client.Receive(data); 37 //轉碼 38 string message = Encoding.UTF8.GetString(data, 0, length); 39 Console.WriteLine("收到了客戶端消息:" + message); 40 //向客戶端發送消息 41 client.Send(Encoding.UTF8.GetBytes("你來了呀")); 42 //流結束時要關閉,遵循先開后關的原則 43 client.Close(); 44 45 tcpServer.Close(); 46 } 47 } 48 }
客戶端:
1 using System; 2 using System.Net.Sockets; 3 using System.Net; 4 using System.Text; 5 6 namespace TCP客戶端 7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 //socket 13 Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 14 //ip 15 IPAddress ipAddress = new IPAddress(new byte[] { 192, 168, 1, 184 }); 16 //ip + Port(端口) 17 IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 6688); 18 //連接服務器端 19 tcpClient.Connect(ipEndPoint); 20 Console.WriteLine("鏈接上服務器端了"); 21 //向服務器發送消息 22 //轉碼為byte字節發送 23 tcpClient.Send(Encoding.UTF8.GetBytes("我連接上了")); 24 //分配1024個字節大小的內存給message 25 byte[] message = new byte[1024]; 26 //接收消息 27 int length = tcpClient.Receive(message); 28 //轉碼為string接收 29 string data = Encoding.UTF8.GetString(message, 0, length); 30 Console.WriteLine("收到服務器消息:" + data); 31 //關閉Socket 32 tcpClient.Close(); 33 } 34 } 35 }
客戶端與服務器連接成功