首頁  >  文章  >  後端開發  >  c#(Socket)同步套接字程式碼範例

c#(Socket)同步套接字程式碼範例

黄舟
黄舟原創
2016-12-22 13:27:131220瀏覽

同步用戶端套接字範例   

下面的範例程式建立一個連接到伺服器的客戶端。該客戶端是用同步套接字產生的,因此掛起客戶端應用程式的執行,直到伺服器回傳回應為止。該應用程式將字串傳送到伺服器,然後在控制台顯示該伺服器傳回的字串。

C# 
using System; 
using System.Net; 
using System.Net.Sockets; 
using Syst () { 
// Data buffer for incoming data. 
byte[] bytes = new byte[1024]; 
// Connect to a remote device. 
try { 
// uses port 11000 on the local computer. 
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()) 
IPAddress ipAddress = ipHostInfo.AddressList[0]; 
IPEndPoint remoteEP =  IPEndPoint(ipAddress,11000);
Socket sender = new Socket (AddressFamily.InterNetwork, 
SocketType.Stream, ProtocolType.Tcp ); 
// Connect the socket to the remote endpoint. Catchcm. .WriteLine("Socket connected to {0}", 
sender.RemoteEndPoint.ToString()); 
// Encode the data string into a byte array. 
byte[
// Send the data through the socket. 
int bytesSent = sender.Send(msg); 
// Receive (bytes); 
Console.WriteLine("Echoed test = {0}", 
Encoding.ASCII.GetString(bytes,0,bytesRec)); 
// Release the socket. 
sender.Shutdown(SocketShutdown.Boths).Yo; ArgumentNullException ane) { 
Console.WriteLine("ArgumentNullException : {0}",ane.ToString()); 
} catch (SocketException.Tose)); 
} catch (SocketException,Tose)); 
} catch ) ); 
} catch (Exception e) { 
Console.WriteLine("Unexpected exception : {0}", e.ToString()); 
} 🠎. ToString( )); 


public static int Main(String[] args) { 
StartClient(); 
return 0; 

}請求的伺服器。此伺服器是用同步套接字產生的, 
因此在等待來自客戶端的連線時掛起伺服器應用程式的執行。該應用程式接收來自客戶端的字串, 
在控制台顯示該字串,然後將該字串回顯到客戶端。來自客戶端的字串必須包含字串“”, 
以發出表示訊息結尾的訊號。



  




C# 
 複製代碼 

using System; 
using 

using System; 
. ; 
public class SynchronousSocketListener { 
// Incoming data from the client. 
public static string data = null; 
public static void StartListening() { 
// Data buffer  Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the  
// host running the application. 
IPHostEntry Info.AddressList[0]; 
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000); 
// 建立一個 TCP/IP 套接字。 
Socket 監聽器 = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp); 
// 將套接字綁定到本地端點並監聽傳入連線。 
嘗試{ 
listener.Bind(localEndPoint); 
listener.Listen(10); 
//開始監聽連線。 
while (true) { 
Console.WriteLine("等待連線..."); 
//程式在等待傳入連線時暫停。 
Socket 處理程序=listener.Accept(); 
資料=空白; 
//需要處理傳入連線。
while (true) { 
bytes = 新位元組[1024]; 
int bytesRec = handler.Receive(bytes); 
data += Encoding.ASCII.GetString(bytes,0,bytesRef. ("") > -1) { 
break; 


//在控制台上顯示資料。 
Console.WriteLine(“收到文字:{0}”,data); 
//將資料回顯給客戶端。
byte[] msg = Encoding.ASCII.GetBytes(data); 
handler.Send(msg); 
handler.Shutdown(SocketShutdown.Both); 
handler.Close();
Console.WriteLine(e.ToString()); 

Console.WriteLine("n按Enter 繼續..."); 
Console.Read(); 
} { 
StartListening(); 
回傳0; 



 以上是c#(Socket)同步原始碼範例的內容,並更多相關內容請追蹤PHP中文網(www.php.cn)!


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn