C#socket Communication Client (connection status monitoring, drop-link reconnection)

Source: Internet
Author: User

Tag: Amp failed connection failed gevent ISS TCO [] Tee mod

public class Socketclientmanager
{
public delegate void Connectstateeventhandler ();
Public event Connectstateeventhandler connectedevent;//Connection succeeded
Public event Connectstateeventhandler disconnectedevent;//Connection failed

public delegate void Receivemsgeventhandler (byte[] order);
public event Receivemsgeventhandler Receivemsgevent;

static Socket _socket = null;
static IPEndPoint IEP = NULL;
static bool isconnecting = FALSE;
static bool isconnected = FALSE;

Public Socketclientmanager (string Strip,int port)
{
_socket = new Socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);
IPAddress IP = Ipaddress.parse (Strip.trim ());
IEP = new IPEndPoint (IP, Port);
}

public void Start ()
{
Isconnecting = true;
Thread t = new thread (Connect);
T.isbackground = true;
T.start ();
}

private void Connect ()
{
while (isconnecting)
{
Try
{
if (! Issocketconnected (_socket) && disconnectedevent! = null)
{
Disconnectedevent ();
IsConnected = false;
_socket = new Socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);
_socket. Connect (IEP);
Connectedevent ();
IsConnected = true;
Thread t = new thread (RECEIVEMSG);
T.isbackground = true;
T.start ();
}
}
Catch {}
Finally
{
Thread.Sleep (500);
}
}
}

private void Receivemsg ()
{
while (isconnected)
{
byte[] buffer = new BYTE[32];
int count = _socket. Receive (buffer);
if (Count > 0&&receivemsgevent! = null)
{
Receivemsgevent (buffer);
}
}
}

public void sendmsg (byte[] order)
{
_socket. Send (order, order. Length, Socketflags.none);
}

private bool Issocketconnected (Socket s)
{
Return! ((S.poll (Selectmode.selectread) && (s.available = = 0)) | |!s.connected);
}
}

C#socket Communication Client (connection status monitoring, drop-link reconnection)

Related Article

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.