




版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
1、套接字簡(jiǎn)介:套接字最早是Unix的,window是借鑒過(guò)來(lái)的。TCP/IP協(xié)議族提供三種套接字:流式、數(shù)據(jù)報(bào)式、原始套接字。其中原始套接字允許對(duì)底層協(xié)議直接訪問(wèn),一般用于檢驗(yàn)新協(xié)議或者新設(shè)備問(wèn)題,很少使用。套接字編程原理:延續(xù)文件作用思想,打開(kāi)-讀寫(xiě)-關(guān)閉的模式。C/S編程模式如下:Ø 服務(wù)器端:打開(kāi)通信通道,告訴本地機(jī)器,愿意在該通道上接受客戶請(qǐng)求監(jiān)聽(tīng),等待客戶請(qǐng)求接受請(qǐng)求,創(chuàng)建專用鏈接進(jìn)行讀寫(xiě)處理完畢,關(guān)閉專用鏈接關(guān)閉通信通道(當(dāng)然其中監(jiān)聽(tīng)到關(guān)閉專用鏈接可以重復(fù)循環(huán))Ø 客戶端:打開(kāi)通信通道,連接服務(wù)器數(shù)據(jù)交互關(guān)閉信道。Soc
2、ket通信方式:Ø 同步:客戶端在發(fā)送請(qǐng)求之后必須等到服務(wù)器回應(yīng)之后才可以發(fā)送下一條請(qǐng)求。串行運(yùn)行Ø 異步:客戶端請(qǐng)求之后,不必等到服務(wù)器回應(yīng)之后就可以發(fā)送下一條請(qǐng)求。并行運(yùn)行套接字模式:Ø 阻塞:執(zhí)行此套接字調(diào)用時(shí),所有調(diào)用函數(shù)只有在得到返回結(jié)果之后才會(huì)返回。在調(diào)用結(jié)果返回之前,當(dāng)前進(jìn)程會(huì)被掛起。即此套接字一直被阻塞在網(wǎng)絡(luò)調(diào)用上。Ø 非阻塞:執(zhí)行此套接字調(diào)用時(shí),調(diào)用函數(shù)即使得不到得到返回結(jié)果也會(huì)返回。套接字工作步驟:Ø 服務(wù)器監(jiān)聽(tīng):監(jiān)
3、聽(tīng)時(shí)服務(wù)器端套接字并不定位具體客戶端套接字,而是處于等待鏈接的狀態(tài),實(shí)時(shí)監(jiān)控網(wǎng)絡(luò)狀態(tài)Ø 客戶端鏈接:客戶端發(fā)出鏈接請(qǐng)求,要連接的目標(biāo)是服務(wù)器端的套接字。為此客戶端套接字必須描述服務(wù)器端套接字的服務(wù)器地址與端口號(hào)。Ø 鏈接確認(rèn):是指服務(wù)器端套接字監(jiān)聽(tīng)到客戶端套接字的鏈接請(qǐng)求時(shí),它響應(yīng)客戶端鏈接請(qǐng)求,建立一個(gè)新的線程,把服務(wù)器端套接字的描述發(fā)送給客戶端,一旦客戶端確認(rèn)此描述,則鏈接建立好。而服務(wù)器端的套接字繼續(xù)處于監(jiān)聽(tīng)狀態(tài),繼續(xù)接受其他客戶端套接字請(qǐng)求。在TCP/IP網(wǎng)絡(luò)中,IP網(wǎng)絡(luò)交互分類兩大類:面向連接的交互與面向無(wú)連接的交互。S
4、ocket構(gòu)造函數(shù):public socket(AddressFamily 尋址類型, SocketType 套接字類型, ProtocolType 協(xié)議類型)。但需要注意的是套接字類型與協(xié)議類型并不是可以隨便組合。SocketTypeProtocolType描述StreamTcp面向連接DgramUdp面向無(wú)連接RawIcmp網(wǎng)際消息控制RawRaw基礎(chǔ)傳輸協(xié)議Socket類的公共屬性:屬性名描述AddressFamily獲取Socket的地址族Available獲取已經(jīng)從網(wǎng)絡(luò)接收且可供讀取的數(shù)據(jù)量Blocking獲取或設(shè)置一個(gè)值,只是socket是否處于阻塞模
5、式Connected獲取一個(gè)值,指示當(dāng)前連接狀態(tài)Handle獲取socket的操作系統(tǒng)句柄LocalEndPoint獲取本地終端EndPointRemoteEndPoint獲取遠(yuǎn)程終端EndPointProtocolType獲取協(xié)議類型SocketType獲取SocketType類型Socket常用方法:Bind(EndPoint)服務(wù)器端套接字需要綁定到特定的終端,客戶端也可以先綁定再請(qǐng)求連接Listen(int)監(jiān)聽(tīng)端口,其中parameters表示最大監(jiān)聽(tīng)數(shù)Accept()接受客戶端鏈接,并返回一個(gè)新的鏈接,用于處理同客戶端的通信問(wèn)題 Send()發(fā)送數(shù)據(jù)Send(byte)簡(jiǎn)
6、單發(fā)送數(shù)據(jù)Send(byte,SocketFlag)使用指定的SocketFlag發(fā)送數(shù)據(jù)Send(byte, int, SocketFlag)使用指定的SocketFlag發(fā)送指定長(zhǎng)度數(shù)據(jù)Send(byte, int, int, SocketFlag)使用指定的SocketFlag,將指定字節(jié)數(shù)的數(shù)據(jù)發(fā)送到已連接的socket(從指定偏移量開(kāi)始)Receive()接受數(shù)據(jù)Receive(byte)簡(jiǎn)單接受數(shù)據(jù)Receive (byte,SocketFlag)使用指定的SocketFlag接受數(shù)據(jù)Receive (byte, int, SocketFlag)使用指定的SocketFlag接受指
7、定長(zhǎng)度數(shù)據(jù)Receive (byte, int, int, SocketFlag)使用指定的SocketFlag,從綁定的套接字接收指定字節(jié)數(shù)的數(shù)據(jù),并存到指定偏移量位置的緩沖區(qū) Connect(EndPoint)連接遠(yuǎn)程服務(wù)器ShutDown(SocketShutDown)禁用套接字,其中SocketShutDown為枚舉,Send禁止發(fā)送,Receive為禁止接受,Both為兩者都禁止Close()關(guān)閉套接字,釋放資源異步通信方法:BeginAccept(AsynscCallBack,object)開(kāi)始一個(gè)一步操作接受一個(gè)連接嘗試。參數(shù):一個(gè)委托。一個(gè)對(duì)象。對(duì)象包含此請(qǐng)求的狀態(tài)信
8、息。其中回調(diào)方法中必須使用EndAccept方法。應(yīng)用程序調(diào)用BegineAccept方法后,系統(tǒng)會(huì)使用單獨(dú)的線程執(zhí)行指定的回調(diào)方法并在EndAccept上一直處于阻塞狀態(tài),直至監(jiān)測(cè)到掛起的鏈接。EndAccept會(huì)返回新的socket對(duì)象。供你來(lái)同遠(yuǎn)程主機(jī)數(shù)據(jù)交互。不能使用返回的這個(gè)socket接受隊(duì)列中的任何附加連接。調(diào)用BeginAccept當(dāng)希望原始線程阻塞的時(shí)候,請(qǐng)調(diào)用WaitHandle.WaitOne方法。當(dāng)需要原始線程繼續(xù)執(zhí)行時(shí)請(qǐng)?jiān)诨卣{(diào)方法中使用ManualResetEvent的set方法BeginConnect(EndPoint, AsyncCallBack, Object)
9、回調(diào)方法中必須使用EndConnect()方法。Object中存儲(chǔ)了連接的詳細(xì)信息。BeginSend(byte, SocketFlag, AsyncCallBack, Object) BegineReceive(byte, SocketFlag, AsyncCallBack, Object) BegineDisconnect(bool, AsyncCallBack, Object) 給出同步通信與異步通信的示例:同步通信:預(yù)定義結(jié)構(gòu)體,同步通信沒(méi)有多線程異步委托回調(diào),所以無(wú)需預(yù)定義結(jié)構(gòu)體客戶端Client:class Program
10、0; static void Main() try int port =
11、 2000; string host = "" IPAddress ip = IPAddress.Parse(host);
12、0; IPEndPoint ipe = new IPEndPoint(ip, port);/把ip和端口轉(zhuǎn)化為IPEndPoint實(shí)例 Socket c = new Socket(Ad
13、dressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);/創(chuàng)建一個(gè)Socket Console.WriteLine("Conneting.");
14、 c.Connect(ipe);/連接到服務(wù)器 string sendStr = "hello!This is a socket test" byte bs
15、= Encoding.ASCII.GetBytes(sendStr); Console.WriteLine("Send Message"); c.Send(bs, bs.Length, 0)
16、;/發(fā)送測(cè)試信息 string recvStr = "" byte recvBytes = new byte1024;
17、60; int bytes; bytes = c.Receive(recvBytes, recvBytes.Length, 0);/從服務(wù)器端接受返回信息
18、0; recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes); Console.WriteLine("Client Get Message:0", recvStr);/顯示服務(wù)器返回信息
19、60; c.Close(); catch (ArgumentNullException e)
20、 Console.WriteLine("ArgumentNullException: 0", e); catch (SocketException e)
21、160; Console.WriteLine("SocketException: 0", e); Console.W
22、riteLine("Press Enter to Exit"); Console.ReadLine(); 服務(wù)器端:class Program static void Main()
23、160; try int port = 2000; string host = ""
24、; IPAddress ip = IPAddress.Parse(host); IPEndPoint ipe = new IPEndPoint(ip, port); Socket s = new Socket(Ad
25、dressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);/創(chuàng)建一個(gè)Socket類 s.Bind(ipe);/綁定2000端口 s.Listen(0);/開(kāi)始監(jiān)聽(tīng)
26、60; Console.WriteLine("Wait for connect"); Socket temp = s.Accept();/為新建連接創(chuàng)建新的Socket。 Console.WriteLine("Get
27、a connect"); string recvStr = "" byte recvBytes = new byte1024;
28、 int bytes; bytes = temp.Receive(recvBytes, recvBytes.Length, 0);/從客戶端接受信息 recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
29、; Console.WriteLine("Server Get Message:0", recvStr);/把客戶端傳來(lái)的信息顯示出來(lái) string sendStr = "Ok!Client Send Message Sucessful!"
30、160; byte bs = Encoding.ASCII.GetBytes(sendStr); temp.Send(bs, bs.Length, 0);/返回客戶端成功信息 temp.Close()
31、; s.Close(); catch (ArgumentNullException e) Console.
32、WriteLine("ArgumentNullException: 0", e); catch (SocketException e) Console.WriteLine("SocketException: 0", e);
33、; Console.WriteLine("Press Enter to Exit"); Console.ReadLine(); 異步通信:客戶端Client:預(yù)定義結(jié)構(gòu)體,用于異步委托之間的傳遞。用戶根據(jù)自己需要定制即可public class StateObject / Client socket. &
34、#160; public Socket workSocket = null; / Size of receive buffer. public const int BufferSize = 256; / Receive buffer. public byte buffer = new byteBufferSize;
35、 / Received data string. public StringBuilder sb = new StringBuilder();正文:public class AsynchronousClient / The port number for the remote device. private const int
36、0;port = 11000; / ManualResetEvent instances signal completion. private static ManualResetEvent connectDone = new ManualResetEvent(false); private static ManualResetEvent sendDone = new&
37、#160;ManualResetEvent(false); private static ManualResetEvent receiveDone = new ManualResetEvent(false); / The response from the remote device.private static String response = String.Empty;
38、160; private static void StartClient() / Connect to a remote device. try / Establish the remote endpoint for the so
39、cket. / The name of the remote device is "". IPHostEntry ipHostInfo = Dns.Resolve("");
40、 IPAddress ipAddress = ipHostInfo.AddressList0; IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
41、/ Create a TCP/IP socket. Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.T
42、cp); / Connect to the remote endpoint. client.BeginConnect(remoteEP,
43、 new AsyncCallback(ConnectCallback), client); connectDone.WaitOne(); / Send test data to the remote device.
44、 Send(client, "This is a test<EOF>"); sendDone.WaitOne(); / Receive the response fro
45、m the remote device. Receive(client); receiveDone.WaitOne(); / Write the response
46、 to the console. Console.WriteLine("Response received : 0", response); / Release the socket.
47、160; client.Shutdown(SocketShutdown.Both); client.Close(); catch (Exception e) Conso
48、le.WriteLine(e.ToString(); private static void ConnectCallback(IAsyncResult ar) try /
49、 Retrieve the socket from the state object. Socket client = (Socket)ar.AsyncState; / Complete the connection.
50、160; client.EndConnect(ar); Console.WriteLine("Socket connected to 0", client.RemoteEndPo
51、int.ToString(); / Signal that the connection has been made. connectDone.Set();
52、160; catch (Exception e) Console.WriteLine(e.ToString(); private static void Receive(Socket client)
53、 try / Create the state object. StateObject state = new StateObject();
54、160; state.workSocket = client; / Begin receiving the data from the remote device. client.BeginReceive(state.buffer,
55、0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state); catch (Exception
56、;e) Console.WriteLine(e.ToString(); private static void ReceiveCallback(IAsyncResult ar)
57、160;try / Retrieve the state object and the client socket / from the asynchronous state object.
58、60; StateObject state = (StateObject)ar.AsyncState; Socket client = state.workSocket; / Read data from the remote device.
59、0; int bytesRead = client.EndReceive(ar); if (bytesRead > 0) /
60、 There might be more data, so store the data received so far. state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead);
61、160; / Get the rest of the data. client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
62、60; new AsyncCallback(ReceiveCallback), state); else
63、; / All the data has arrived; put it in response. if (state.sb.Length > 1)
64、0; response = state.sb.ToString();
65、60; / Signal that all bytes have been received. receiveDone.Set();
66、160; catch (Exception e) Console.WriteLine(e.ToString(); private static void Send(Sock
67、et client, String data) / Convert the string data to byte data using ASCII encoding. byte byteData = Encoding.ASCII.GetBytes(data); &
68、#160; / Begin sending the data to the remote device. client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client);
69、0; private static void SendCallback(IAsyncResult ar) try / Retrieve the socket from the state object.
70、160; Socket client = (Socket)ar.AsyncState; / Complete sending the data to the remote device.
71、 int bytesSent = client.EndSend(ar); Console.WriteLine("Sent 0 bytes to server.", bytesSent); / Signal that all bytes have bee
72、n sent. sendDone.Set(); catch (Exception e) Console.WriteLine(e.ToString();
73、160; public static int Main(String args) StartClient(); return 0; 服務(wù)器端Server:預(yù)定義結(jié)構(gòu)體,用于異步委托之間的傳遞。同客戶端的一致。不再贅述正文:/ Sta
74、te object for reading client data asynchronouslypublic class AsynchronousSocketListener / Thread signal. public static ManualResetEvent allDone = new ManualResetEvent(false); public Asynchron
75、ousSocketListener() public static void StartListening() / Data buffer for incoming data. byte bytes = new Byte1024; &
76、#160; / Establish the local endpoint for the socket. / The DNS name of the computer / running the listener is "". /IPHos
77、tEntry ipHostInfo = Dns.Resolve(Dns.GetHostName(); IPHostEntry ipHostInfo = Dns.Resolve(""); IPAddress ipAddress = ipHostInfo.AddressList0;
78、60; IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000); / Create a TCP/IP socket. Socket listener = new Socket(AddressFamily.InterNetwork,SocketType.Stream,
79、ProtocolType.Tcp); / Bind the socket to the local endpoint and listen for incoming connections. try listener.Bind(localEndPoint);
80、 listener.Listen(100); while (true) / Set the event to nonsignal
81、ed state. allDone.Reset(); / Start an asynchronous socket to listen for connections.
82、160; Console.WriteLine("Waiting for a connection."); listener.BeginAccept(new AsyncCallback(AcceptCallback),listener); &
83、#160; / Wait until a connection is made before continuing. allDone.WaitOne();
84、60; catch (Exception e) Console.WriteLine(e.ToString();
85、60;Console.WriteLine("nPress ENTER to continue."); Console.Read(); public static void AcceptCallback(IAsyncResult ar)
86、; / Signal the main thread to continue. allDone.Set(); / Get the socket that handles the client request. Socket listener = (Socket)ar.AsyncStat
87、e; Socket handler = listener.EndAccept(ar); / Create the state object. StateObject state = new StateObject();
88、 state.workSocket = handler; handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,newAsyncCallback(ReadCallback), state); public static void ReadCallback(IAsy
89、ncResult ar) String content = String.Empty; / Retrieve the state object and the handler socket / from the asynchronous s
90、tate object. StateObject state = (StateObject)ar.AsyncState; Socket handler = state.workSocket; / Read data from the client socket.
91、 int bytesRead = handler.EndReceive(ar); if (bytesRead > 0) / There m
92、ight be more data, so store the data received so far. state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead); / Check for end-of-file tag. If it
93、 is not there, read / more data. content = state.sb.ToString(); if (content.IndexO
94、f("<EOF>") > -1) / All the data has been read from the / client. Display it on the console. Console.WriteLine("Read 0 bytes from socket. n Data : 1", content.Length, content
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 溝槽砂石墊層施工方案
- 液壓鋼板壩施工方案
- 端墻施工方案
- TSHAEPI 001-2022 凈味環(huán)保瀝青氣態(tài)污染物減排性能技術(shù)要求
- DLT-637-1997-閥控式密封鉛酸蓄電池訂貨技術(shù)條件
- 二零二五年度設(shè)備安裝安全協(xié)議及設(shè)備安裝驗(yàn)收證書(shū)
- 二零二五年度房地產(chǎn)租賃稅務(wù)籌劃與合同管理服務(wù)協(xié)議
- 二零二五年度住宅及地下室使用權(quán)租賃合同
- 2025年度智能化綠植養(yǎng)護(hù)服務(wù)合同協(xié)議書(shū)模板
- 二零二五年度珠寶店電子商務(wù)平臺(tái)合作開(kāi)發(fā)合同
- 2023年青島遠(yuǎn)洋船員職業(yè)學(xué)院高職單招(數(shù)學(xué))試題庫(kù)含答案解析
- GB/T 25137-2010鈦及鈦合金鍛件
- 公司安全生產(chǎn)管理架構(gòu)圖
- 服飾禮儀四三七三七一一五
- 團(tuán)課知識(shí)點(diǎn)考團(tuán)課必備
- 測(cè)量基礎(chǔ)知識(shí)和操作培訓(xùn) 課件
- 第2課《說(shuō)和做》課件(共30張ppt) 部編版語(yǔ)文七年級(jí)下冊(cè)
- 文言文之荀子《勸學(xué)》完美課件
- 計(jì)算機(jī)常見(jiàn)故障的判斷和維修課件
- 《鐵道車(chē)輛工程》第05章鐵道車(chē)輛的運(yùn)行性能課件
- 七上解一元一次方程100道練習(xí)題(有答案)
評(píng)論
0/150
提交評(píng)論