C# An existing connection was forcibly closed by the remote host: socket programming

前端 未结 2 1825
北海茫月
北海茫月 2020-12-11 12:16

I am working with sockets. Here are my codes (the description of problem is further):

Client side:

    public void ReadCallback(IAsy         


        
相关标签:
2条回答
  • 2020-12-11 12:46

    You are getting an exception from handler.EndReceive(). While admittedly it is unclear why you’re receiving the specific exception you mentioned, when put into production this code will throw exceptions every time there is a network communication problem (which is common).

    Therefore, you should probably put a try/catch around the call to EndReceive() anyway. Think about what your code would need to do whenever the connection fails or the server dies or whatever.

    Then you can start diagnosing specific problems. One important thing you haven’t specified: do you get this error only occasionally or do you reproducibly get it all the time? If it’s the former, then it might just be normal Internet connectivity fluctuations. Your software will have to be able to handle those. If it’s the latter, then I think it sounds like a problem on the server. When you call BeginReceive(), your system will start waiting for something from the server; if that “something” is that it received data, then EndReceive() will succeed, but if that “something” is that the server has closed the connection, your callback will still be invoked, and then EndReceive() will throw the relevant SocketException. This is by design because there’s pretty much no other way to communicate to your code that the server has closed the connection.

    EDIT: Looks like your server code needs the same error handling: its call to EndReceive() is equally prone to throwing an exception if the client closes the connection. (I know you have a try/catch around the whole big thing, but it outputs a MessageBox... that is not going to work well on a server, unless you want someone sitting there all the time clicking on all the OK buttons...)

    0 讨论(0)
  • 2020-12-11 13:00

    Based on your error, I'm not sure the problem is with your code, it may be on the server. Beyond adding some state checking to validate that handler.EndReceive(ar) will return something useful, you'll probably need to check the server itself (or ask the people who maintain it to do so) to see why it's closing the connection on you.

    In the end, the problem code could be in your initial code, instead of in this piece: say, if the intial call to the server is too long and causes a timeout or deadlock.

    0 讨论(0)
提交回复
热议问题