C#socket Communication Server (Connection status monitoring)

Source: Internet
Author: User

Class Socketservermanager
{
public delegate void Connectstateeventhandler ();
Public event Connectstateeventhandler connectedevent;//Client Connection
Public event Connectstateeventhandler disconnectedevent;//client off-line

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

static Socket _socket = null;
static IPEndPoint IEP = NULL;
static bool islistening = FALSE;
static bool isconnected = FALSE;
Static Dictionary<endpoint, socket> dic = null;
static EndPoint EP = null;

Public Socketservermanager (string Strip,int port)
{
_socket = new Socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);
IPAddress IP = Ipaddress.parse (Strip.trim ());
IEP = new IPEndPoint (IP, Port);
Dic=new dictionary<endpoint,socket> ();
}

public void Start ()
{
_socket. Bind (IEP);
Islistening = true;
Thread t = new thread (Listen);
T.isbackground = true;
T.start ();
}

private void Listen ()
{
while (islistening)
{
_socket. Listen (0);
Socket Newsocket = _socket. Accept ();
if (connectedevent! = null) connectedevent ();
EP = Newsocket. Remoteendpoint;
Dic. ADD (EP, Newsocket);
IsConnected = true;
thread T1 = new Thread (RECEIVEMSG);
T1. IsBackground = true;
T1. Start ();
}
}

private void Receivemsg ()
{
while (isconnected)
{
Byte[] Buffer=new byte[32];
int count = Dic[ep]. Receive (buffer);
if (Count > 0&&receivemsgevent! = null)
{
Receivemsgevent (buffer);
}
if (! Issocketconnected (Dic[ep]) && disconnectedevent! = null)
{
Disconnectedevent ();
IsConnected = false;
}
Thread.Sleep (200);
}
}

public void sendmsg (byte[] order)
{
DIC[EP]. Send (Order,order. Length,socketflags.none);
}

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

C#socket Communication Server (Connection status monitoring)

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.