Use asynchronous socket programming in C # To implement the C/S communication architecture of TCP network services (ii) ---- usage
I. How to Use tcpsvr
A. Test procedure:
Using system;
Using IBMs. net. tcpcsframework;
Using system. collections;
Using system. net. Sockets;
Namespace IBMs. Test
{
/// <Summary>
/// Test the tcpsvr class
/// </Summary>
Public class testtcpsvr
{
Public testtcpsvr ()
{
}
Public static void main ()
{
Try
{
Console. writeline ("begin to test tcpsvr class ...");
Testtcpsvr TTS = new testtcpsvr ();
// Tcpsvr SVR = new tcpsvr (9050,4); // encoding. default encoding is used by default.
Tcpsvr SVR = new tcpsvr (9050,4, new coder (CODER. encodingmothord. utf8 ));
SVR. resovlver = new datagramresolver ("##");
// Define four events of the server
// The server is full
SVR. serverfull + = new netevent (TTS. serverfull );
// New client connection
SVR. clientconn + = new netevent (TTS. clientconn );
// Close the client
SVR. clientclose + = new netevent (TTS. clientclose );
// Receive data
SVR. recvdata + = new netevent (TTS. recvdata );
// Command Control Loop
While (true)
{
Console. Write ("> ");
String cmd = console. Readline ();
// Exit the test program
If (CMD. tolower () = "exit ")
{
Break;
}
// Stop the server program
If (CMD. tolower () = "stop ")
{
SVR. Stop ();
Console. writeline ("server is stop .");
Continue;
}
// Run the server program
If (CMD. tolower () = "start ")
{
SVR. Start ();
Console. writeline ("server is listen... {0 }",
SVR. serversocket. localendpoint. tostring ());
Continue;
}
// View the number and capacity of online clients on the server
If (CMD. tolower () = "count ")
{
Console. writeline ("current count of client is {0}/{1 }",
SVR. sessioncount, SVR. capacity );
Continue;
}
// Send data to the client. Format: Send [session] [stringdata]
If (CMD. tolower (). indexof ("send ")! =-1)
{
Cmd = cmd. tolower ();
String [] para = cmd. Split ('');
If (para. Length = 3)
{
Session client = (Session) SVR. sessiontable [New sessionid (Int. parse
(Para [1])];
If (client! = NULL)
{
SVR. Send (client, para [2]);
}
Else
{
Console. writeline ("the session is null ");
}
}
Else
{
Console. writeline ("error command ");
}
Continue;
}
// Kill a client from the server
If (CMD. tolower (). indexof ("kick ")! =-1)
{
Cmd = cmd. tolower ();
String [] para = cmd. Split ('');
If (para. Length = 2)
{
Session client = (Session) SVR. sessiontable [New sessionid (Int. parse
(Para [1])];
If (client! = NULL)
{
SVR. closesession (client );
}
Else
{
Console. writeline ("the session is null ");
}
}
Else
{
Console. writeline ("error command ");
}
Continue;
}
// List all client information on the server
If (CMD. tolower () = "list ")
{
Int I = 0;
Foreach (Session client in SVR. sessiontable. values)
{
If (client! = NULL)
{
I ++;
String info = string. Format ("{0} client: {1} Connected Server session: {2}. Socket handle: {3 }",
I,
Client. clientsocket. remoteendpoint. tostring (),
Client. ID,
Client. clientsocket. Handle );
Console. writeline (Info );
}
Else
{
I ++;
String info = string. Format ("{0} null client", I );
Console. writeline (Info );
}
}
Continue;
}
Console. writeline ("unkown command ");
} // End of while
Console. writeline ("End Service ");
}
Catch (exception ex)
{
Console. writeline (ex. tostring ());
}
}
Void clientconn (Object sender, neteventargs E)
{
String info = string. Format ("a client: {0} connect Server session: {1}. Socket handle: {2 }",
E. Client. clientsocket. remoteendpoint. tostring (),
E. Client. ID, E. Client. clientsocket. Handle );
Console. writeline (Info );
Console. Write ("> ");
}
Void serverfull (Object sender, neteventargs E)
{
String info = string. Format ("server is full. The client: {0} is refused ",
E. Client. clientsocket. remoteendpoint. tostring ());
// Must do it
// When the server is full, the new client connection must be closed.
E. Client. Close ();
Console. writeline (Info );
Console. Write ("> ");
}
Void clientclose (Object sender, neteventargs E)
{
String Info;
If (E. Client. typeofexit = session. exittype. exceptionexit)
{
Info = string. Format ("A Client Session: {0} exception closed .",
E. Client. ID );
}
Else
{
Info = string. Format ("A Client Session: {0} normal closed .",
E. Client. ID );
}
Console. writeline (Info );
Console. Write ("> ");
}
Void recvdata (Object sender, neteventargs E)
{
String info = string. Format ("Recv daTa: {0} from: {1}. ", E. Client. datax, E. Client );
Console. writeline (Info );
Tcpsvr SVR = (tcpsvr) sender;
// The test returns the received data to the client.
SVR. Send (E. Client, E. Client. datax );
Console. Write ("> ");
}
}
}
B. Description:
Use commands to operate servers
Exit
Start Service
Kick closes the client
Send data
List lists the statuses of all clients.
Count client count
Start the service and wait for the client to connect.
Then you can use list and count to view the current connection status.
Each event has a corresponding function, and the customer processes their own business logic in the event processing function.
You can inherit your own server applications with the basic framework unchanged.
Ii. Usage of tcpcli
A. Test procedure:
Using system;
Using IBMs. net. tcpcsframework;
Namespace IBMs. Test
{
/// <Summary>
/// Summary of testtcpclient.
/// </Summary>
Public class testtcpclient
{
Public testtcpclient ()
{
//
// Todo: add the constructor logic here
//
}
Public static void test ()
{
Console. writeline ("begin to test tcpcli class ..");
Testtcpclient test = new testtcpclient ();
Tcpcli CLI = new tcpcli (New coder (CODER. encodingmothord. utf8 ));
CLI. resovlver = new datagramresolver ("##");
CLI. receiveddatasync + = new netevent (test. recvdata );
CLI. disconnectedserver + = new netevent (test. clientclose );
CLI. connectedserver + = new netevent (test. clientconn );
Try
{
// Command Control Loop
While (true)
{
Console. Write ("> ");
String cmd = console. Readline ();
If (CMD. tolower () = "exit ")
{
Break;
}
If (CMD. tolower () = "close ")
{
CLI. Close ();
Continue;
}
If (CMD. tolower (). indexof ("conn ")! =-1)
{
Cmd = cmd. tolower ();
String [] para = cmd. Split ('');
If (para. Length = 3)
{
CLI. Connect (para [1], Int. parse (para [2]);
}
Else
{
Console. writeline ("error command ");
}
Continue;
}
If (CMD. tolower (). indexof ("send ")! =-1)
{
Cmd = cmd. tolower ();
String [] para = cmd. Split ('');
If (para. Length = 2)
{
CLI. Send (para [1]);
}
Else
{
Console. writeline ("error command ");
}
Continue;
}
Console. writeline ("unkown command ");
} // End of while
Console. writeline ("End Service ");
}
Catch (exception ex)
{
Console. writeline (ex. tostring ());
}
}
Void clientconn (Object sender, neteventargs E)
{
String info = string. Format ("a client: {0} connect server: {1}", E. client,
E. Client. clientsocket. remoteendpoint. tostring ());
Console. writeline (Info );
Console. Write ("> ");
}
Void clientclose (Object sender, neteventargs E)
{
String Info;
If (E. Client. typeofexit = session. exittype. exceptionexit)
{
Info = string. Format ("A Client Session: {0} exception closed .",
E. Client. ID );
}
Else
{
Info = string. Format ("A Client Session: {0} normal closed .",
E. Client. ID );
}
Console. writeline (Info );
Console. Write ("> ");
}
Void recvdata (Object sender, neteventargs E)
{
String info = string. Format ("Recv daTa: {0} from: {1}. ", E. Client. datax, E. Client );
Console. writeline (Info );
Console. Write ("> ");
}
}
}
B. Description:
First establish a connection, Conn 192.9.207.214 9050
Then you can send data
Close the connection
Iii. Encoder
If you want to encrypt your packets, you need your own coder.
Inherit a class such as mycoder from the coder class, and then reload the encoding and decoding functions.
Usage:
Tcpcli CLI = new tcpcli (New mycoder ());
The encoder can be used on the client.
Iv. Message parser
The same implementation method as the encoder.