简体   繁体   English

如何区分套接字中的读取错误和写入错误?

[英]How do I tell apart a read error from a write error in a socket?

I am creating a server for a game that deals with lots of TCP connections, and I need to deal with a sudden loss of connection (pc crash, game process killed, internet connection lost, ectect). 我正在为一个处理大量TCP连接的游戏创建服务器,并且我需要处理突然的连接丢失(电脑崩溃,游戏进程中断,互联网连接丢失等)。 The problem I currently have is that I can't tell apart a read error from a write error since both throw an IOException . 我目前遇到的问题是我无法区分读取错误和写入错误,因为两者都抛出IOException even the underlying exception is the same ( SocketException ), the only difference being that one occurs on Socket.Send() and the other on Socket.Receive() respectively. 甚至基本的异常是相同的( SocketException ),是一个唯一的差别发生在Socket.Send()而另一个上Socket.Receive()分别。 I could of course compare the exception message, but that would become a problem as soon as the system language changes (and lets be honest, that would be a pretty messy approach anyway). 我当然可以比较异常消息,但是一旦系统语言发生更改,那将成为一个问题(老实说,无论如何这都是一种非常混乱的方法)。

I tried comparing the Hresult but since the underlying exception is the same, so is the Hresult . 我尝试比较Hresult但由于基本异常相同,因此Hresult也是Hresult I also tried getHashCode() but this one changes from player to player. 我也尝试过getHashCode()但是这一点因播放器而getHashCode()

Any other ways I could tell apart those 2 situations? 我还有其他方法可以区分这两种情况吗? To clarify, we're talking about the exception that comes up when using TcpClient.read() or TcpClient.write() on a TcpClient whose connection has been unexpectedly closed. 为澄清起见,我们正在讨论在连接意外关闭的TcpClient上使用TcpClient.read()TcpClient.write()时出现的异常。

You could try wrapping the send and receive functions in a try-catch block, and use the Data property to tell exceptions from read and write apart: 您可以尝试将发送和接收函数包装在try-catch块中,并使用Data属性来区分读写异常:

enum ReadOrWrite { Read, Write }

void Foo()
{
    try
    {
        socket.Receive();
    }
    catch (IOException ex)
    {
        ex.Data.Add("readOrWrite", ReadOrWrite.Read);
        throw;
    }
}

And this is where you later catch it: 这是您稍后捕获的地方:

try
{
    Foo();
}
catch (IOException ex) when (ex.Data.Contains("readOrWrite"))
{
    var readOrWrite = ex.Data["readOrWrite"];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM