简体   繁体   中英

System.Net.Sockets.SocketException (0x80004005)

I'm writing a bot for moderating my twitch.tv channel in C#.

Here's the basic code for the loop, which is done by a background worker to avoid UI freezes. There's a TCPClient (Client), StreamReader (Reader), StreamWriter (Writer), and NetworkStream (Stream).

    private void listener_dowork(object sender, DoWorkEventArgs e)
    {
        string Data = "";
        while ((Data = Reader.ReadLine()) != null)
        {
            //Perform operations on the received data
        }
        Console.WriteLine("Loop ended");//this shouldn't happen
    }
    private void listener_workercompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        //basically, display a console message that says "OOPS!" and try to reconnect.
    }

I get the message "Loop ended" and "OOPS!" and at that point, I get the exception (which I cannot for the life of me catch).

The thing is, I can physically unplug the network cable from my computer wait 30 seconds and plug it back in, and it'll continue just fine.

The full exception is:

System.Net.Sockets.SocketException (0x80004005): An established connection was aborted by the software in your host machine
   at System.Net.Sockets.Socket.Send(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
   at System.Net.Sockets.NetworkStream.Write(Byte[] buffer, Int32 offset, Int32 size)

Note the lack of a line number, which is present in every other kind of exception I've had, which means I have no idea which part of the program is causing the exception, even though I've put every possible line inside a try/catch.

I guess what I'm looking for is some insight into why this is occurring.

It happens invariably every time I start the bot and leave it running for a few minutes on any channel, though the number of minutes varies.

As I already said in the comments Twitch.tv uses IRC as underlying system for their chat. In order to stay connected with the server you need to reply to "PING" requests that are frequently sent by the server (usually every 30 seconds, may vary depending on the servers implementation). You can read up more about the IRC client protocol in RFC 2812 .

You said you already have a StreamWriter and Reader, all you need to do is check if the line contains "PING" and reply with a "PONG":

if (Data.Contains("PING"))
{
  _streamWriter.WriteLine(Data.Replace("PING","PONG");
  _streamWriter.Flush();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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