支付寶 收費(fèi) 網(wǎng)站開(kāi)發(fā)東莞seo
---部分截圖來(lái)自 siki學(xué)院Unity網(wǎng)絡(luò)通訊課程
Socket?
網(wǎng)絡(luò)上的兩個(gè)程序通過(guò)一個(gè)雙向的通信連接實(shí)現(xiàn)數(shù)據(jù)交換,這個(gè)連接的一端稱(chēng)為一個(gè) Socket ,Socket 包含了網(wǎng)絡(luò)通信必須的五種信息
Socket 例子{?
協(xié)議: TCP
本地: IP ,端口
遠(yuǎn)程: IP ,端口
}
可以通過(guò)ipconfig,netstat? ?-ano 查看 Ip 和端口
創(chuàng)建客戶(hù)端連接服務(wù)端
客戶(hù)端代碼:
using System;
using System.Net.Sockets;namespace wangluo
{class Program{static void Main(string[] args){//創(chuàng)建一個(gè)Socket 需要using System.Net.Sockets;Socket tempClient = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);tempClient.Connect("127.0.0.1", 8888);}}
}
服務(wù)端代碼:
using System;
using System.Net.Sockets;
using System.Net;namespace Server
{class Program{static void Main(string[] args){Socket tempServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);IPEndPoint tempEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888); //using System.Net;tempServer.Bind(tempEndPoint); //綁定端口tempServer.Listen(0); //監(jiān)聽(tīng),0表示掛起的隊(duì)列無(wú)限長(zhǎng)Console.WriteLine("服務(wù)端啟動(dòng)成功");Socket tempConnectClient = tempServer.Accept();Console.WriteLine("客戶(hù)端連接成功:" + tempConnectClient);}}
}
先開(kāi)啟服務(wù)端再開(kāi)啟客戶(hù)端?
客戶(hù)端服務(wù)端互發(fā)信息
客戶(hù)端代碼:
using System;
using System.Net.Sockets;
using System.Text;namespace wangluo
{class Program{static void Main(string[] args){//創(chuàng)建一個(gè)Socket 需要using System.Net.Sockets;Socket tempClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);tempClient.Connect("127.0.0.1", 8888);//客戶(hù)端向服務(wù)端發(fā)信息string tempSendInfo = Console.ReadLine();//將字符串轉(zhuǎn)換成 bufferbyte[] tempSendData = Encoding.UTF8.GetBytes(tempSendInfo);//發(fā)送信息tempClient.Send(tempSendData);//接收來(lái)自服務(wù)端的信息byte[] tempReadBuffer = new byte[1024];tempClient.Receive(tempReadBuffer);string tempReadString = Encoding.UTF8.GetString(tempReadBuffer);Console.WriteLine("接收到服務(wù)端信息:" + tempReadString);}}
}
服務(wù)端代碼:
using System;
using System.Net.Sockets;
using System.Net;
using System.Text;namespace Server
{class Program{static void Main(string[] args){Socket tempServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);IPEndPoint tempEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888); //using System.Net;tempServer.Bind(tempEndPoint); //綁定端口tempServer.Listen(0); //監(jiān)聽(tīng),0表示掛起的隊(duì)列無(wú)限長(zhǎng)Console.WriteLine("服務(wù)端啟動(dòng)成功");Socket tempConnectClient = tempServer.Accept();Console.WriteLine("客戶(hù)端連接成功:" + tempConnectClient);byte[] tempReadBuffer = new byte[1024];tempConnectClient.Receive(tempReadBuffer);//將 byte 轉(zhuǎn)換成字符串string tempReadString = Encoding.UTF8.GetString(tempReadBuffer);Console.WriteLine("接收到客戶(hù)端信息:" + tempReadString);//服務(wù)端向客戶(hù)端發(fā)信息string tempSendInfo = Console.ReadLine();byte[] tempSendData = Encoding.UTF8.GetBytes(tempSendInfo);tempConnectClient.Send(tempSendData);}}
}
封裝一下代碼:
客戶(hù)端:
using System;
using System.Net.Sockets;
using System.Text;namespace wangluo
{class Program{static void Main(string[] args){//創(chuàng)建一個(gè)Socket 需要using System.Net.Sockets;Socket tempClient = CreateSocket();tempClient.Connect("127.0.0.1", 8888);Send(tempClient);Receive(tempClient);}static Socket CreateSocket(){return new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);}static void Send(Socket tempClient){//客戶(hù)端向服務(wù)端發(fā)信息string tempSendInfo = Console.ReadLine();//將字符串轉(zhuǎn)換成 bufferbyte[] tempSendData = Encoding.UTF8.GetBytes(tempSendInfo);//發(fā)送信息tempClient.Send(tempSendData);}static void Receive(Socket tempClient){//接收來(lái)自服務(wù)端的信息byte[] tempReadBuffer = new byte[1024];tempClient.Receive(tempReadBuffer);string tempReadString = Encoding.UTF8.GetString(tempReadBuffer);Console.WriteLine("接收到服務(wù)端信息:" + tempReadString);}}
}
?服務(wù)端:
using System;
using System.Net.Sockets;
using System.Net;
using System.Text;namespace Server
{class Program{static void Main(string[] args){Socket tempServer = CreateSocket();BindAndListen(tempServer);Socket tempConnectClient = Accept(tempServer);Receive(tempConnectClient);Send(tempConnectClient);}static Socket CreateSocket(){return new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);}static void BindAndListen(Socket pSocket){IPEndPoint tempEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888); //using System.Net;pSocket.Bind(tempEndPoint); //綁定端口pSocket.Listen(0); //監(jiān)聽(tīng),0表示掛起的隊(duì)列無(wú)限長(zhǎng)Console.WriteLine("服務(wù)端啟動(dòng)成功");}static Socket Accept(Socket pSocket){Socket tempConnectClient = pSocket.Accept();Console.WriteLine("客戶(hù)端連接成功:" + tempConnectClient);return tempConnectClient;}static void Receive(Socket pSocket){byte[] tempReadBuffer = new byte[1024];pSocket.Receive(tempReadBuffer);//將 byte 轉(zhuǎn)換成字符串string tempReadString = Encoding.UTF8.GetString(tempReadBuffer);Console.WriteLine("接收到客戶(hù)端信息:" + tempReadString);}static void Send(Socket pSocket){//服務(wù)端向客戶(hù)端發(fā)信息string tempSendInfo = Console.ReadLine();byte[] tempSendData = Encoding.UTF8.GetBytes(tempSendInfo);pSocket.Send(tempSendData);}}
}
Socket 代碼解析:
AddressFamily: InterNetwork 使用IPv4 ? ?InterNetworkV6 使用IPv6
SocketType:
異步
客戶(hù)端:異步 Connect
// Main
tempClient.BeginConnect("127.0.0.1", 8888, ConnectCallback, tempClient);static void ConnectCallback(IAsyncResult ar){//beginconnect函數(shù)中最后一個(gè)參數(shù)就是用來(lái)作為callback的參數(shù)使用//將其由 object 類(lèi)型強(qiáng)制轉(zhuǎn)換成 socket 類(lèi)型Socket tempSocket = (Socket)ar.AsyncState;//與 BeginConnect 配套的 EndConnect//異步的結(jié)束tempSocket.EndConnect(ar);Console.WriteLine("連接服務(wù)器成功");Send(tempSocket);Receive(tempSocket);Close(tempSocket);}
異步 Receive
//接收來(lái)自服務(wù)端的信息 調(diào)用 Receive 的地方tempSocket.BeginReceive(tempReadBuffer, 0, 1024,SocketFlags.None, ReceiveCallback, tempSocket);static void ReceiveCallback(IAsyncResult ar){ Socket tempSocket = (Socket)ar.AsyncState;tempSocket.EndReceive(ar);string tempReadString = Encoding.UTF8.GetString(tempReadBuffer);Console.WriteLine("接收到服務(wù)端信息:" + tempReadString);Close(tempSocket);}
異常處理:
static void ReceiveCallback(IAsyncResult ar){try{Socket tempSocket = (Socket)ar.AsyncState;tempSocket.EndReceive(ar);string tempReadString = Encoding.UTF8.GetString(tempReadBuffer);Console.WriteLine("接收到服務(wù)端信息:" + tempReadString);Close(tempSocket);}catch (Exception ex){Console.WriteLine("連接異常" + ex.ToString());}}
異步send
tempClient.BeginSend(tempSendData,0,tempSendData.Length,SocketFlags.None, SendCallback, tempClient);static void SendCallback(IAsyncResult ar){try{Socket tempSocket = (Socket)ar.AsyncState;tempSocket.EndSend(ar);Console.WriteLine("發(fā)送數(shù)據(jù)成功");}catch (Exception ex){Console.WriteLine("發(fā)送異常");}
總覽:
using System;
using System.Net.Sockets;
using System.Text;namespace wangluo
{class Program{static private byte[] tempReadBuffer = new byte[1024];static void Main(string[] args){//創(chuàng)建一個(gè)Socket 需要using System.Net.Sockets;Socket tempClient = CreateSocket();tempClient.BeginConnect("127.0.0.1", 8888, ConnectCallback, tempClient);System.Threading.Thread.Sleep(1000);}static Socket CreateSocket(){return new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);}static void Send(Socket tempClient){//客戶(hù)端向服務(wù)端發(fā)信息string tempSendInfo = Console.ReadLine();//將字符串轉(zhuǎn)換成 bufferbyte[] tempSendData = Encoding.UTF8.GetBytes(tempSendInfo);//發(fā)送信息tempClient.BeginSend(tempSendData,0,tempSendData.Length,SocketFlags.None, SendCallback, tempClient);}static void Close(Socket pSocket){pSocket.Close();}static void ConnectCallback(IAsyncResult ar){//beginconnect函數(shù)中最后一個(gè)參數(shù)就是用來(lái)作為callback的參數(shù)使用//將其由 object 類(lèi)型強(qiáng)制轉(zhuǎn)換成 socket 類(lèi)型Socket tempSocket = (Socket)ar.AsyncState;//與 BeginConnect 配套的 EndConnect//異步的結(jié)束tempSocket.EndConnect(ar);Console.WriteLine("連接服務(wù)器成功");Send(tempSocket);//接收來(lái)自服務(wù)端的信息tempSocket.BeginReceive(tempReadBuffer, 0, 1024, SocketFlags.None, ReceiveCallback, tempSocket);}static void ReceiveCallback(IAsyncResult ar){try{Socket tempSocket = (Socket)ar.AsyncState;tempSocket.EndReceive(ar);string tempReadString = Encoding.UTF8.GetString(tempReadBuffer);Console.WriteLine("接收到服務(wù)端信息:" + tempReadString);Close(tempSocket);}catch (Exception ex){Console.WriteLine("接收失敗" + ex.ToString());}}static void SendCallback(IAsyncResult ar){try{Socket tempSocket = (Socket)ar.AsyncState;tempSocket.EndSend(ar);Console.WriteLine("發(fā)送數(shù)據(jù)成功");}catch (Exception ex){Console.WriteLine("發(fā)送異常");}}}
}
服務(wù)端:異步 Accept
//main
tempServer.BeginAccept(AcceptCallback, tempServer);static void AcceptCallback(IAsyncResult ar){try{Socket tempSeverSocket = (Socket)ar.AsyncState;Socket tempClientSocket = tempSeverSocket.EndAccept(ar);Console.WriteLine("客戶(hù)端接收成功:" + ((IPEndPoint)tempClientSocket.RemoteEndPoint));Receive(tempClientSocket);Send(tempClientSocket);}catch (Exception ex){Console.WriteLine("接收客戶(hù)端失敗");}}
服務(wù)端:異步Send和異步Receive
using System;
using System.Net.Sockets;
using System.Net;
using System.Text;namespace Server
{class Program{static byte[] readBuffer = new byte[1024];static void Main(string[] args){Socket tempServer = CreateSocket();BindAndListen(tempServer);tempServer.BeginAccept(AcceptCallback, tempServer);System.Threading.Thread.Sleep(1000);}static Socket CreateSocket(){return new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);}static void BindAndListen(Socket pSocket){IPEndPoint tempEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888); //using System.Net;pSocket.Bind(tempEndPoint); //綁定端口pSocket.Listen(0); //監(jiān)聽(tīng),0表示掛起的隊(duì)列無(wú)限長(zhǎng)Console.WriteLine("服務(wù)端啟動(dòng)成功");}static void Send(Socket pSocket){//服務(wù)端向客戶(hù)端發(fā)信息string tempSendInfo = Console.ReadLine();byte[] tempSendData = Encoding.UTF8.GetBytes(tempSendInfo);pSocket.BeginSend(tempSendData, 0, tempSendData.Length, SocketFlags.None, SendCallback, pSocket);}static void Close(Socket pSocket){pSocket.Close();}static void AcceptCallback(IAsyncResult ar){try{Socket tempSeverSocket = (Socket)ar.AsyncState;Socket tempClientSocket = tempSeverSocket.EndAccept(ar);Console.WriteLine("客戶(hù)端接收成功:" + ((IPEndPoint)tempClientSocket.RemoteEndPoint));tempClientSocket.BeginReceive(readBuffer, 0, 1024, SocketFlags.None,ReceiveCallback, tempClientSocket);Send(tempClientSocket);}catch (Exception ex){Console.WriteLine("接收客戶(hù)端失敗");}}static void ReceiveCallback(IAsyncResult ar){try{Socket tempSocket = (Socket)ar.AsyncState;tempSocket.EndReceive(ar);string tempReadString = Encoding.UTF8.GetString(readBuffer);Console.WriteLine("接收到客戶(hù)端信息:" + tempReadString);Close(tempSocket);}catch (Exception ex){Console.WriteLine("接收失敗" + ex.ToString());}}static void SendCallback(IAsyncResult ar){try{Socket tempSocket = (Socket)ar.AsyncState;tempSocket.EndSend(ar);Console.WriteLine("發(fā)送數(shù)據(jù)成功");}catch (Exception ex){Console.WriteLine("發(fā)送異常");}}}
}
讓服務(wù)端支持多個(gè)客戶(hù)端連接
//用來(lái)存放連接到的客戶(hù)端private static List<Socket> clientList = new List<Socket>();static void AcceptCallback(IAsyncResult ar){Socket tempSeverSocket = (Socket)ar.AsyncState;Socket tempClientSocket = tempSeverSocket.EndAccept(ar);Console.WriteLine("客戶(hù)端接收成功:" + ((IPEndPoint)tempClientSocket.RemoteEndPoint));tempClientSocket.BeginReceive(readBuffer, 0, 1024, SocketFlags.None,ReceiveCallback, tempClientSocket);tempSeverSocket.BeginAccept(AcceptCallback, tempSeverSocket);clientList.Add(tempClientSocket);Send(tempClientSocket);;}
HTTP協(xié)議
C#使用 http 協(xié)議的示例:?
private static void Get(){HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.metools.info");request.Method = "GET";//request.AcceptHttpWebResponse response = (HttpWebResponse)request.GetResponse();response.GetResponseStream();Stream responseStream = response.GetResponseStream();string result = new StreamReader(responseStream).ReadToEnd();Console.WriteLine(result);}