我遇到了某个问题。我的契约(Contract)实现(除了其他东西)是这样的:
try
{
response = _socketRequest.SendRequest(request, emmiterHeader);
trCode = response.TraceCodeInt;
if (trCode == 0)
statusRequest = (int) TSRequestAttemptStatus.active;
}
catch (TimeoutException tex)
{
throw;
}
catch (Exception)
{
statusRequest = (int) TSRequestAttemptStatus.notActive;
throw;
}
finally
{
tsra = CreateTireaSincoRequestAttemptRow(DateTime.Now, statusRequest, emmiterHeader.HeaderId,
string.Empty,
string.Empty,
string.Empty,
previousContractNumber,
taxIdentificationCode,
policyHolderName,
policyHolderFirstName,
policyHolderLastName,
registrationNumberType.Substring(0, 1),
registrationNumber,
((byte) ControlCodes.F),
DateTime.Now.AddDays(emmiterHeader.ValidityPeriod));
}
然后在
_socketRequest.SendRequest(请求, emmiterHeader);
除其他内容外,还有如下内容:
using (var client = new TcpClient(header.SocketServerAddress,
header.SocketServerPort == null ? 1 : (int)header.SocketServerPort))
{
Socket socket = client.Client;
// send data with timeout 10s
//socket.Send(arr);
Send(socket, arr, 0, arr.Length, 1000);
if (header.DebugMode)
_logger.LogInfo(InterfaceName, string.Format("Data Socket Send: {0} ", tempArr));
// receive data with timeout 10s
//Receive(client, arr);
len = Receive(socket, arrResponse, 0, arrResponse.Length, 5000, header.DebugMode, _logger);
if (socket.Connected)
socket.Close();
if (client.Connected)
client.Close();
}
永远不会调用 using 关键字下的部分,因为内置的 WCF 客户端在 TCPClient 部分“挂起”,总之会引发 SocketExeption 错误。我已将网络配置中的超时设置为 5 秒。我想实现的是不抛出套接字异常而是抛出超时异常。看起来 SocketException 被抛出,但我无法让我的 wcf 服务抛出超时异常。有可能这样做吗?我希望我的问题是可以理解的,我想做什么。如果没有,我会尽量解释清楚。
最佳答案
TcpClient 不知道也不关心你在和什么通话。它没有 WCF、Web 服务或您想要的 TimeoutException
的概念。
它所做的一切都是为了维护 TCP 连接。
捕获SocketException
并分析其中存储的错误代码。有一个超时代码。自己抛出 TimeoutException
。
并摆脱这种迷信的处理方式:
if (socket.Connected)
socket.Close();
if (client.Connected)
client.Close();
一次就够了。
关于c# - 如何使用 TcpClient 类在 WCF 中获取超时异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24493541/