非同步客戶端套接字範例
下面的範例程式建立一個連接到伺服器的客戶端。該客戶端是用非同步套接字產生的,因此在等待伺服器回傳回應時不掛起客戶端應用程式的執行。該應用程式將字串傳送到伺服器,然後在控制台顯示該伺服器傳回的字串。
C#
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading; p. eiving data from remote device.
public class StateObject {
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
public class AsynchronousClient port = 11000;
// ManualResetEvent instances signal completion.
private static ManualResetEvent connectDone =
new ManualResetEvent(false);
private static ManualResetEvent sendcom iveDone =
new ManualResetEvent(false);
// The response from the remote device.
private static String response = String.Empty;
private static void StartClient() {
// Connect to a remotec/pointo. the socket.
// The name of the
// remote device is "host.contoso.com".
IPHostEntry ipHostInfo = Dns.Resolve("host.contoso.com");
IPAddress ipAddressP=cListip.com");
IPAddress Address, port) ;
// Create a TCP/IP socket.
Socket client = new Socket(AddressFamily.InterNetwork,
client.BeginConnect( remoteEP,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
// Send test data to the remote device.
Send(client,"This) ;
// Receive the response from the remote device.
Receive(client);
receiveDone.WaitOne();
// : {0}", response);
// Release the socket.
client.Shutdown(SocketShutdown.Both);
client.Close();
} catch (ExceptionStringC) {
private static void ConnectCallback(IAsyncResult ar) {
try {
// Retrieve the socket from the the connection.
client.EndConnect(ar);
Console .WriteLine("Socket connected to {0}",
client.RemoteEndPoint.ToString());
// Signal that the connection been made. {
Console .WriteLine(e.ToString());
}
}
private static void Receive(Socket client) {
try { /
state.workSocket = client ;
// Begin receiving the data from the remote device.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
} catch (異常e) {
Console.WriteLinee.
private static void ReceiveCallback( IAsyncResult ar ) {
try {
// 從非同步狀態物件擷取狀態物件與客戶端套接字
// 從非同步狀態物件擷取狀態物件和客戶端套接字
///
///
//。
StateObject 狀態 = (StateObject) ar.AsyncState;
Socket 用戶端 = state.workSocket;
//從遠端裝置讀取資料。
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0) {
//可能有更多數據,因此儲存目前收到的資料。
state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));
//取得其餘資料。
client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,
new AsyncCallback(ReceiveCallback), state);
} else {
// 所有資料已到達中。
if (state.sb.Length > 1) {
response = state.sb.ToString();
}
// 表示所有位元組都已收到。
receiveDone.Set();
}
} catch(異常e){
Console.WriteLine(e.ToString());
}
}
private statSoid Soidsprivate statS), private statS/oid, private statS), private statS), private statS oid/S; ASCII 編碼將字串資料轉換為位元組資料。
byte[] byteData = Encoding.ASCII.GetBytes(data);
//開始將資料傳送至遠端設備。
client.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), client);
}
狀態物件檢索套接字。
Socket 用戶端=(Socket) ar.AsyncState;
//完成將資料傳送至遠端裝置。
int bytesSent = client.EndSend(ar);
Console.WriteLine("已發送 {0} 個位元組到伺服器。", bytesSent);
// 發出所有位元組已傳送的訊號。
sendDone.Set();
} catch (異常e) {
Console.WriteLine(e.ToString());
}
}
public static int Main(String[) 0;
}
}
非同步架構範例 下面的範例程式建立接收來自客戶端的連線請求的伺服器。該伺服器是使用非同步架構產生的,
因此等待在來自客戶端的連接時不掛起伺服器應用程式的執行。該應用程式接收來自客戶端的字串,
在控制台顯示該字串,然後將字串回顯到客戶端。來自客戶端的字串必須包含字串“
以發出表示訊息結束的訊號。
C#
使用系統複製程式碼
;
使用System.
// 用於非同步讀取客戶端資料的狀態物件
public class StateObject {
// 客戶端套接字。
public Socket workSocket = null;
//接收緩衝區的大小。
公 const int BufferSize = 1024;
//接收緩衝區。
public byte[] buffer = new byte[BufferSize];
//收到資料字串。
public StringBuilder sb = new StringBuilder();
}
公共類別 AsynchronousSocketListener {
// 執行緒訊號。
public static ManualResetEvent allDone = new ManualResetEvent(false);
public AsynchronousSocketListener() {
}
public static void StartListening() {
// 用於傳入資料的資料緩衝區。
byte[]位元組=新位元組[1024];
// 為套接字建立本地端點。
// 執行偵聽器的電腦的 DNS 名稱是「host.contoso.com」。
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IP 1(ip/pcom
Socket 監聽器 = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
//將套接字綁定到本地端點並偵聽傳入連線。
嘗試{
listener.Bind(localEndPoint);
listener.Listen(100);
while (true) {
//將事件設為無訊號狀態。
allDone.Reset();
//啟動非同步套接字來偵聽連線。
Console.WriteLine("正在等待連線...");
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
//等待連線建立後再繼續。
allDone.WaitOne();
}
} catch(異常e){
Console.WriteLine(e.ToString());
}
Console.WriteLine("n) 按下
}
Console.WriteLine("n)。 Read();
}
public static void AcceptCallback(IAsyncResult ar) {
// 向主執行緒發出訊號繼續。
allDone.Set();
//取得處理客戶端請求的套接字。
Socket 監聽器 = (Socket) ar.AsyncState;
Socket 處理程序=listener.EndAccept(ar);
//建立狀態物件。
StateObject 狀態= new StateObject();
state.workSocket = 處理程序;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncmCallback(Readallback)
}; ReadCallback(IAsyncResult ar){
String content = String.Empty;
//從非同步狀態物件擷取狀態物件和處理程序套接字。
StateObject 狀態 = (StateObject) ar.AsyncState;
Socket 處理程序 = state.workSocket;
//從客戶端套接字讀取資料。
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0) {
//可能有更多數據,因此儲存目前收到的資料。
state.sb.Append(Encoding.ASCII.GetString(
state.buffer,0,bytesRead));
//檢查檔案結尾標記。 如果不存在,請閱讀
//更多資料。
內容 = state.sb.ToString();
if (content.IndexOf("
// 所有資料已從
// 客戶端讀取。 將其顯示在控制台上。
Console.WriteLine("從套接字讀取 {0} 個位元組。資料:{1}",
content.Length, content);
//將資料回顯給客戶端。
寄送(處理程序,內容);
} 其他 {
// 未收到所有資料。 得到更多。
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
}
}
private statis vleal vk oid, 片
ASCII 編碼將字串資料轉換為位元組資料。
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device. handler.Beginend(byteData,c.com)(byc),com SendCallback), handler) ;
}
private static void SendCallback(IAsyncResult ar) {
try {
// Retrieve the socket. ncState;
// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
handler.Shutdown(SocketShutler. (Exception e) {
Console.WriteLine(e.ToString());
}
}
public static int Main(String[]
以上就是c#(Socket)非同步套接字程式碼範例的內容,更多相關內容請關注PHP中文網(www.php.cn)!

JVM的工作原理是將Java代碼轉換為機器碼並管理資源。 1)類加載:加載.class文件到內存。 2)運行時數據區:管理內存區域。 3)執行引擎:解釋或編譯執行字節碼。 4)本地方法接口:通過JNI與操作系統交互。

JVM使Java實現跨平台運行。 1)JVM加載、驗證和執行字節碼。 2)JVM的工作包括類加載、字節碼驗證、解釋執行和內存管理。 3)JVM支持高級功能如動態類加載和反射。

Java應用可通過以下步驟在不同操作系統上運行:1)使用File或Paths類處理文件路徑;2)通過System.getenv()設置和獲取環境變量;3)利用Maven或Gradle管理依賴並測試。 Java的跨平台能力依賴於JVM的抽象層,但仍需手動處理某些操作系統特定的功能。

Java在不同平台上需要進行特定配置和調優。 1)調整JVM參數,如-Xms和-Xmx設置堆大小。 2)選擇合適的垃圾回收策略,如ParallelGC或G1GC。 3)配置Native庫以適應不同平台,這些措施能讓Java應用在各種環境中發揮最佳性能。

Osgi,Apachecommonslang,JNA和JvMoptionsareeForhandlingForhandlingPlatform-specificchallengesinjava.1)osgimanagesdeppedendendencenciesandisolatescomponents.2)apachecommonslangprovidesitorityfunctions.3)

JVMmanagesgarbagecollectionacrossplatformseffectivelybyusingagenerationalapproachandadaptingtoOSandhardwaredifferences.ItemploysvariouscollectorslikeSerial,Parallel,CMS,andG1,eachsuitedfordifferentscenarios.Performancecanbetunedwithflagslike-XX:NewRa

Java代碼可以在不同操作系統上無需修改即可運行,這是因為Java的“一次編寫,到處運行”哲學,由Java虛擬機(JVM)實現。 JVM作為編譯後的Java字節碼與操作系統之間的中介,將字節碼翻譯成特定機器指令,確保程序在任何安裝了JVM的平台上都能獨立運行。

Java程序的編譯和執行通過字節碼和JVM實現平台獨立性。 1)編寫Java源碼並編譯成字節碼。 2)使用JVM在任何平台上執行字節碼,確保代碼的跨平台運行。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

SublimeText3漢化版
中文版,非常好用

WebStorm Mac版
好用的JavaScript開發工具

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)