There are still some shortcomings in this category. Please give more comments to facilitate correction !! Download the Library: csockets.rar
Socketstart. CSCode:
Using system;
Using system. text;
Using system. net;
Using system. net. Sockets;
Using system. Threading;
Using system. collections;
Namespace csockets
{
Public Delegate void getclientid (Object sender, clientid E );
Public class socketstart
{
Public event getclientid monconnected = NULL;
Public arraylist clinetlist = arraylist. synchronized (New arraylist ());
Public asynccallback clientcallback;
Public socket maisocket;
Public int clientnum = 0;
Public void start () // start the service
{
Try
{
Maisocket = new socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP );
Ipendpoint locip = new ipendpoint (IPaddress. Any, 1680 );
Maisocket. BIND (locip );
Maiso cket. Listen (100 );
Maisocket. beginaccept (New asynccallback (clinetconnection), null );
}
Catch (exception E)
{
}
}
Private void clinetconnection (iasyncresult Asyn) // implement multi-customer connection
{
Try
{
Socket clientsocket = maisocket. endaccept (Asyn );
Interlocked. increment (ref clientnum );
Clinetlist. Add (clientsocket );
Monconnected (this, new clientid (this ));
Waidata (clientsocket, clientnum );
Maisocket. beginaccept (New asynccallback (clinetconnection), null );
}
Catch (exception E)
{
}
}
public class socketpack
{< br> Public socket csocketname;
Public byte [] databuffer = new byte [64];
Public int CID;
Public socketpack (Socket socket, int ID)
{< br> csocketname = socket;
cid = ID;
}< BR >}
Private void waidata (socket socketdata, int num) // wait for Data
{
Try
{
If (clientcallback = NULL)
{
Clientcallback = new asynccallback (ondata );
}
Socketpack sp = new socketpack (socketdata, num );
Socketdata. beginreceive (sp. databuffer, 0, sp. databuffer. length, socketflags. None, clientcallback, SP );
}
Catch (exception E)
{
}
}
Private void ondata (iasyncresult asny) // receives data
{
Socketpack sp = (socketpack) asny. asyncstate;
Try
{
Int irx = sp. csocketname. endreceive (asny );
Char [] chars = new char [irx + 1];
String iddata = new string (chars );
String [] STR = iddata. Split (New char [] {'| '});
If (STR [0] = "mes ")
{
}
Waidata (sp. csocketname, sp. CID );
}
Catch (objectdisposedexception SE)
{
}
Catch (socketexception E)
{
If (E. errorcode = 10054)
{
Clinetlist [sp. CID-1] = NULL;
Monconnected (this, new clientid (this ));
}
}
}
Public void sendmess (string sendtext, int sendid) // send data
{
Try
{
Byte [] senddata = system. Text. encoding. utf8.getbytes (sendtext );
Socket sendsocket = (socket) clinetlist [sendid];
Sendsocket. Send (senddata );
}
Catch (exception E)
{
}
}
}
}
The second clientid. CS code:
Using system;
Using system. Collections. Generic;
Using system. text;
Using system. net;
Using system. net. Sockets;
Using system. collections;
Namespace csockets
{
Public class clientid
{
Public clientid (socketstart SS)
{
}
}
}