How to deal with the disconnection of the server or client after the socket connection

Source: Internet
Author: User
Symptom: the server waits for the client to disconnect. When the socket connection is established, if the client is disconnected abnormally, the server throws an exception, resulting in Program Operation interrupted
Objective: To keep the server waiting for connection, the program does not exit after the client is interrupted, and the client can continue to be connected after being restored.
Code :
Public class receive
{
Public static byte [] buffer = new byte [1, 1024];

Public static manualresetevent socketevent = new manualresetevent (false );
Public static socket slistener = new socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP );
Public static socket handler = NULL;
Public static string clientbroken = "An connection was forcibly closed by the remote host ";

Public static void receive ()
{
Try
{
Console. writeline ("Main threadid:" + appdomain. getcurrentthreadid ());
Byte [] bytes = new byte [1, 1024];

IPaddress ipaddr = IPaddress. parse ("127.0.0.1 ");

Int Port = 10001;

Ipendpoint epserver = new ipendpoint (ipaddr, Port );

// Binding a socket
Slistener. BIND (epserver );

// Start listening
Slistener. Listen (10 );

while (true)
{< br> If (handler = NULL)
{< br> // first must make a connect
console. writeline ("waiting for a connection... ");
// asychronous function for accepting connections
slistener. beginaccept (New asynccallback (acceptcallback), slistener);
socketevent. waitone ();
handler. beginreceive (buffer, 0, buffer. length, 0, new asynccallback (receivecallback), Handler);
socketevent. waitone ();
}< br> else
{< br> console. writeline ("waiting next message... ");
socketevent. reset ();
handler. beginreceive (buffer, 0, buffer. length, 0, new asynccallback (receivecallback), Handler);
socketevent. waitone ();
}< BR >}< br> console. readline ();
}< br> catch (exception e)
{< br> console. writeline (E. tostring ();
}< br> console. readline ();
}

Public static void acceptcallback (iasyncresult AR)
{
Try
{
Console. writeline ("acceptcallback thread ID:" + appdomain. getcurrentthreadid ());
Socket listener = (socket) Ar. asyncstate;
// New socket
Handler = listener. endaccept (AR );
Handler. beginreceive (buffer, 0, buffer. length, 0, new asynccallback (effececallback), Handler );
}
Catch (exception E)
{
Console. writeline (E. tostring ());
}
}

Public static void extends ecallback (iasyncresult AR)
{
String err_message = NULL;
Try
{
Console. writeline ("receivecallback thread ID:" + appdomain. getcurrentthreadid ());

String content = string. empty;
Handler = (socket) Ar. asyncstate;

Int bytesread = handler. endreceive (AR );

// If there is some data...
If (bytesread> 0)
{
// Append It To the main string
Content + = encoding. ASCII. getstring (buffer, 0, bytesread );

// If we encounter the End of message character
If (content. indexof (char) 3)>-1 | content. indexof (char) 16)>-1)
{
Console. writeline ("read" + content. Length + "bytes from socket. \ n data:" + content );
Socketevent. Set ();
}
Else
{
// Otherwise receive the remaining data
Handler. beginreceive (buffer, 0, buffer. length, 0, new asynccallback (effececallback), Handler );
}
}

}
Catch (exception E)
{
Err_message = E. message;
If (err_message.indexof ("an existing connection was forcibly closed by the remote host")>-1)
{
Console. writeline ("an existing connection was forcibly closed by the remote host ");
// Handler. Shutdown (socketshutdown. Both );
// Handler. Close ();

Console. writeline ("waiting for a connection ...");
// Asychronous function for accepting connections
Slistener. beginaccept (New asynccallback (acceptcallback), slistener );
}
Else
{
Console. writeline (E. tostring ());
}
}
}
}
Note: The key lies in the exception handling in the last section. After the receiving is interrupted, the server waits for the receiving again.

Symptom: the client is connected to the server. After the socket connection is established, if the server is disconnected abnormally, the client throws an exception, leading to program running interruption.
Objective: to check whether the client prompts that the program does not exit after the server is interrupted, and the connection can be maintained after the server recovers again.
Code:
Public class asynccomm
{
Public static string theresponse = "";
Public static byte [] buffer = new byte [1, 1024];

Public static manualresetevent socketevent = new manualresetevent (false );
Public static socket sclient = new socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP );
Public static ipendpoint epserver = new ipendpoint (IPaddress. parse ("127.0.0.1"), 10001 );

Public static void send (string data)
{
Byte [] bytedata = NULL;
Bytedata = encoding. ASCII. getbytes (data );

Try
{
If (! Sclient. Connected)
{
Console. writeline (system. datetime. now. tostring ("yyyy-mm-dd hh: mm: SS: ffff") + "" + "Connect begining ...... ");
Sclient. beginconnect (epserver, new asynccallback (connectcallback), sclient );
Socketevent. waitone ();
}
Sclient. beginsend (bytedata, 0, bytedata. length, 0, new asynccallback (sendcallback), sclient );
Socketevent. waitone ();
}
Catch (exception E)
{
Console. writeline ("server side is broken ...");
Socketevent. Reset ();
Return;
}
}

Public static void connectcallback (iasyncresult AR)
{
Try
{
Thread thr = thread. currentthread;
Console. writeline ("connectcallback thread state:" + appdomain. getcurrentthreadid ());

Socket sclient = (socket) Ar. asyncstate;
Sclient. endconnect (AR );
Console. writeline ("Socket connected to" + sclient. remoteendpoint. tostring ());
Socketevent. Set ();
}
Catch (exception ex)
{
Console. writeline (system. datetime. now. tostring ("yyyy-mm-dd hh: mm: SS: ffff") + "|" + appdomain. getcurrentthreadid () + "| 3 -- level 3 server connection is broken, waiting for Level 3 server connection ...... ");
Sclient = new socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP );
Socketevent. Set ();
}
}

The receive function is the same and can be written by reference.
Note:
Check whether the current socket is connected during each sending or receiving. If there is no connection, start the connection and block the thread to wait for connectcallback to return.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.