在C#中,使用Socket連接時(shí),可以通過(guò)設(shè)置ReceiveTimeout
和SendTimeout
屬性來(lái)控制連接超時(shí)。這兩個(gè)屬性分別表示接收和發(fā)送操作的超時(shí)時(shí)間,單位為毫秒。
以下是一個(gè)示例,展示了如何設(shè)置Socket連接的超時(shí)時(shí)間:
using System;
using System.Net;
using System.Net.Sockets;
class Program
{
static void Main(string[] args)
{
// 創(chuàng)建一個(gè)Socket對(duì)象
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 設(shè)置接收超時(shí)時(shí)間(單位:毫秒)
socket.ReceiveTimeout = 5000;
// 設(shè)置發(fā)送超時(shí)時(shí)間(單位:毫秒)
socket.SendTimeout = 5000;
try
{
// 連接到遠(yuǎn)程服務(wù)器
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
int port = 8080;
IPEndPoint remoteEndPoint = new IPEndPoint(ipAddress, port);
socket.Connect(remoteEndPoint);
Console.WriteLine("Connected to server.");
// 接收數(shù)據(jù)
byte[] buffer = new byte[1024];
int receivedBytes = socket.Receive(buffer);
string receivedData = Encoding.ASCII.GetString(buffer, 0, receivedBytes);
Console.WriteLine("Received data: " + receivedData);
// 發(fā)送數(shù)據(jù)
string message = "Hello, server!";
byte[] sendBuffer = Encoding.ASCII.GetBytes(message);
socket.Send(sendBuffer);
Console.WriteLine("Message sent.");
}
catch (SocketException ex)
{
if (ex.SocketErrorCode == SocketError.TimedOut)
{
Console.WriteLine("Connection timed out.");
}
else
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}
finally
{
// 關(guān)閉Socket連接
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
}
}
在這個(gè)示例中,我們創(chuàng)建了一個(gè)Socket對(duì)象,并設(shè)置了接收和發(fā)送操作的超時(shí)時(shí)間。然后,我們嘗試連接到遠(yuǎn)程服務(wù)器,并接收或發(fā)送數(shù)據(jù)。如果在指定的超時(shí)時(shí)間內(nèi)無(wú)法完成這些操作,將拋出一個(gè)SocketException
異常,我們可以捕獲該異常并處理超時(shí)情況。