下面的示例程序创建一个连接到服务器的客户端。该客户端是用异步套接字生成的,因此在等待服务器返回响应时不挂起客户端应用程序的执行。该应用程序将字符串发送到服务器,然后在控制台显示该服务器返回的字符串。
using System; using System.Net; using System.Net.Sockets; using System.Threading; using System.Text; // State object for receiving data from remote device. public class StateObject { // Client socket. public Socket workSocket = null; // Size of receive buffer. public const int BufferSize = 256; // Receive buffer. public byte[] buffer = new byte[BufferSize]; // Received data string. public StringBuilder sb = new StringBuilder(); } public class AsynchronousClient { // The port number for the remote device. private const int port = 11000; // ManualResetEvent instances signal completion. private static ManualResetEvent connectDone = new ManualResetEvent(false); private static ManualResetEvent sendDone = new ManualResetEvent(false); private static ManualResetEvent receiveDone = new ManualResetEvent(false); // The response from the remote device. private static String response = String.Empty; private static void StartClient() { // Connect to a remote device. try { // Establish the remote endpoint for the socket. // The name of the // remote device is "host.contoso.com". IPHostEntry ipHostInfo = Dns.Resolve("host.contoso.com"); IPAddress ipAddress = ipHostInfo.AddressList[0]; IPEndPoint remoteEP = new IPEndPoint(ipAddress, port); // Create a TCP/IP socket. Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Connect to the remote endpoint. client.BeginConnect( remoteEP, new AsyncCallback(ConnectCallback), client); connectDone.WaitOne(); // Send test data to the remote device. Send(client,"This is a test<EOF>"); sendDone.WaitOne(); // Receive the response from the remote device. Receive(client); receiveDone.WaitOne(); // Write the response to the console. Console.WriteLine("Response received : {0}", response); // Release the socket. client.Shutdown(SocketShutdown.Both); client.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } private static void ConnectCallback(IAsyncResult ar) { try { // Retrieve the socket from the state object. Socket client = (Socket) ar.AsyncState; // Complete the connection. client.EndConnect(ar); Console.WriteLine("Socket connected to {0}", client.RemoteEndPoint.ToString()); // Signal that the connection has been made. connectDone.Set(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } private static void Receive(Socket client) { try { // Create the state object. StateObject state = new StateObject(); state.workSocket = client; // Begin receiving the data from the remote device. client.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state); } catch (Exception e) { Console.WriteLine(e.ToString()); } } private static void ReceiveCallback( IAsyncResult ar ) { try { // Retrieve the state object and the client socket // from the asynchronous state object. StateObject state = (StateObject) ar.AsyncState; Socket client = state.workSocket; // Read data from the remote device. int bytesRead = client.EndReceive(ar); if (bytesRead > 0) { // There might be more data, so store the data received so far. state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead)); // Get the rest of the data. client.BeginReceive(state.buffer,0,StateObject.BufferSize,0, new AsyncCallback(ReceiveCallback), state); } else { // All the data has arrived; put it in response. if (state.sb.Length > 1) { response = state.sb.ToString(); } // Signal that all bytes have been received. receiveDone.Set(); } } catch (Exception e) { Console.WriteLine(e.ToString()); } } private static void Send(Socket client, String data) { // Convert the string data to byte data using ASCII encoding. byte[] byteData = Encoding.ASCII.GetBytes(data); // Begin sending the data to the remote device. client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client); } private static void SendCallback(IAsyncResult ar) { try { // Retrieve the socket from the state object. Socket client = (Socket) ar.AsyncState; // Complete sending the data to the remote device. int bytesSent = client.EndSend(ar); Console.WriteLine("Sent {0} bytes to server.", bytesSent); // Signal that all bytes have been sent. sendDone.Set(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } public static int Main(String[] args) { StartClient(); return 0; } }
本文分享自華爲雲社區《Python網絡編程實踐從Socket到HTTP協議的探索與實現》,作者:檸檬味擁抱。 在當今互聯網時代,網絡編程是程序員不可或缺的一項技能。Python作爲一種高級編程語言,提供了豐富的網絡編程庫,使得開發者能夠輕鬆
最近需要在uos上部署系統,考慮用docker會簡單一些,但uos默認沒有docker,於是嘗試安裝。兩種安裝方法,1是改安裝源地址然後yum或dnf安裝;2是手動下載靜態包安裝。原則上1簡單一些,但爲了更好理解docker的運行邏輯,選擇
雲棲號資訊:【點擊查看更多行業資訊】在這裏您可以找到不同行業的第一手的上雲資訊,還在等什麼,快來! 前言 單例應用的太廣泛,大家應該都用過,本文主要是想聊聊線程安全的單例以及反序列化破壞單例的情況。 1、概念 確保某一個類只有一個實例,而
Xmake 是一個基於 Lua 的輕量級跨平臺構建工具。 它非常的輕量,沒有任何依賴,因爲它內置了 Lua 運行時。 它使用 xmake.lua 維護項目構建,相比 makefile/CMakeLists.txt,配置語法更加簡潔直觀,
簡介: 搶紅包是我們生活常用的社交功能, 這個功能最主要的特點就是用戶的併發請求高, 在系統設計上, 可以使用非常多的辦法來扛住用戶的高併發請求, 在本文中簡要介紹使用Redis緩存中間件來實現搶紅包算法, Redis是一個在內存中基
字符串是 Java 程序中最常用的數據結構之一。在 Java 中 String 類已經重載了"+",字符串可以直接使用"+"進行連接,也可以用StringBuilder/StringBuffer(StringBuilder是J2SE5 及以
Java 平臺提供了兩種類型的字符串操作方式:String 和 StringBuffer/StringBuilder,它們都可以儲存和操作字符串,區別如下: String 是隻讀字符串,也就意味着 String 引用的字符串內容是不能被改
1 枚舉好用嗎? 數據字典型字段,枚舉比Integer好: 限定值,只能賦值枚舉的那幾個實例,不能像Integer隨便輸,保存和查詢的時候特別有用 含義明確,使用時不需要去查數據字典 顯示值跟存儲值直接映射,不需要手動轉換,比如1在頁面上
1 概述 通道是Golang提供的一種基本類型,它可以實現在協程之間的單向通信和雙向通信、發送和接收數據、以及協程同步。 channel的本質是一個隊列,遵循先進先出原則。channel是線程安全的,在任何給定時間,一個數據被設計爲只有一
簡介 go-python Python提供了豐富的C-API。而C和Go又可以通過cgo無縫集成。所以,直接通過Golang調用libpython,就可以實現Go調Python的功能了。但是過程比較複雜,而go-python提供了針對CPy
雲棲號資訊:【點擊查看更多行業資訊】在這裏您可以找到不同行業的第一手的上雲資訊,還在等什麼,快來! 之前本人在找工作面試時在Redis相關問題上可栽了跟頭。在面試前按常規套路準備了一下,比如 Redis 的常用5種數據結構,Redis持久化
雲棲號資訊:【點擊查看更多行業資訊】在這裏您可以找到不同行業的第一手的上雲資訊,還在等什麼,快來! 本文要點 即將於 2020 年 9 月發佈的 Java SE 15 將引入“封印類(sealed class)”(JEP 360),並將其作
雲棲號資訊:【點擊查看更多行業資訊】在這裏您可以找到不同行業的第一手的上雲資訊,還在等什麼,快來! 簡介 Spring Boot 2.2.0 版本開始引入 JUnit 5 作爲單元測試默認庫,在 Spring Boot 2.2.0 版本之前
阿里雲最佳實踐頻道:【點擊查看更多上雲最佳實踐】這裏有豐富的企業上雲最佳實踐,從典型場景入門,提供一系列項目實踐方案,降低企業上雲門檻的同時滿足您的需求! 場景描述 很多客戶最開始使用雲的時候,會把雲(服務器)簡單地當成普通的物理服務器
雲棲號資訊:【點擊查看更多行業資訊】在這裏您可以找到不同行業的第一手的上雲資訊,還在等什麼,快來! 【導讀】近日,由阿里雲 20+ 位雲原生技術專家共同編撰的《雲原生架構白皮書》正式對外發布。作爲業界第一本全方位構建雲原生架構規劃與實踐全景