同步客戶端套接字示例
下面的示例程序創建一個連接到服務器的客戶端
C#
using System;
using System
using System
using System
public class SynchronousSocketClient {
public static void StartClient() {
// Data buffer for incoming data
byte[] bytes = new byte[
// Connect to a remote device
try {
// Establish the remote endpoint for the socket
// This example uses port
IPHostEntry ipHostInfo = Dns
IPAddress ipAddress = ipHostInfo
IPEndPoint remoteEP = new IPEndPoint(ipAddress
// Create a TCP/IP socket
Socket sender = new Socket(AddressFamily
SocketType
// Connect the socket to the remote endpoint
try {
sender
Console
sender
// Encode the data string into a byte array
byte[] msg = Encoding
// Send the data through the socket
int bytesSent = sender
// Receive the response from the remote device
int bytesRec = sender
Console
Encoding
// Release the socket
sender
sender
} catch (ArgumentNullException ane) {
Console
} catch (SocketException se) {
Console
} catch (Exception e) {
Console
}
} catch (Exception e) {
Console
}
}
public static int Main(String[] args) {
StartClient();
return
}
}
同步服務器套接字示例 下面的示例程序創建一個接收來自客戶端的連接請求的服務器
因此在等待來自客戶端的連接時掛起服務器應用程序的執行
在控制台顯示該字符串
以發出表示消息結尾的信號
C#
復制代碼
using System;
using System
using System
using System
public class SynchronousSocketListener {
// Incoming data from the client
public static string data = null;
public static void StartListening() {
// Data buffer for incoming data
byte[] bytes = new Byte[
// Establish the local endpoint for the socket
// Dns
// host running the application
IPHostEntry ipHostInfo = Dns
IPAddress ipAddress = ipHostInfo
IPEndPoint localEndPoint = new IPEndPoint(ipAddress
// Create a TCP/IP socket
Socket listener = new Socket(AddressFamily
SocketType
// Bind the socket to the local endpoint and
// listen for incoming connections
try {
listener
listener
// Start listening for connections
while (true) {
Console
// Program is suspended while waiting for an incoming connection
Socket handler = listener
data = null;
// An incoming connection needs to be processed
while (true) {
bytes = new byte[
int bytesRec = handler
data += Encoding
if (data
break;
}
}
// Show the data on the console
Console
// Echo the data back to the client
byte[] msg = Encoding
handler
handler
handler
}
} catch (Exception e) {
Console
}
Console
Console
}
public static int Main(String[] args) {
StartListening();
return
}
}
From:http://tw.wingwit.com/Article/program/net/201311/12914.html