If there are server programs, chatserver and client program chatclient, the client can send messages to the server.
Operation steps,
1. Start listen on the server,
2. Connect the client.
3. The client sends messages
As long as the server starts listen, and the client also connects. After the connection is established, it is convenient to accept the sending information. You only need to use writer and reader to operate networkstream.
Server chatserver
Create a winform page
Reference namespace:
Using system. net. Sockets;
Using system. net;
Using system. IO;
Using system. Threading;
Public class chatserver
{
Private int Port = 54321; // port number
Private IPaddress IP = IPaddress. parse ("10.20.30.40"); // ip address
Private tcplistener = NULL;
Private tcpclient = NULL;
Private networkstream = NULL;
Private binaryreader reader;
// Private binarywriter writer;
Private string getinfo = string. empty;
// Start listening
Private void btnstartlisten_click(Object sender, eventargs E)
{
Tcplistener = new tcplistener (IP, Port );
Tcplistener. Start (); // start listening
Thread acceptclientmsgthread = new thread (acceptclientmsg); // run a thread to process information sent from the client
Acceptclientmsgthread. Start ();
}
// Process Information sent from the client
Private void acceptclientmsg ()
{
Tcpclient = tcplistener. accepttcpclient ();
If (tcpclient! = NULL)
{
Networkstream = tcpclient. getstream ();
Reader = new binaryreader (networkstream );
While (true ){
Getinfo + = reader. readstring (); // read the information sent from the client
}
}
}
// If you want to display more information, you can display the entire button (of course, the best way is to use some threads)
// Click the button to display txtshowclientmsg. Text = getinfo;
// If the server wants to send a message to the client, you can add the following code:
// String sendmsg = txtsendmsge. text;
// Writer = new binarywriter (networkstream );
// Writer. Write (sendmsg );
}
Client chatclient
Using system. net. Sockets;
Using system. net;
Using system. IO;
Using system. Threading;
Public class chatclient
{
Private int Port = 54321;
Private IPaddress IP = IPaddress. parse ("10.20.30.40 ");
Private tcpclient = NULL;
Private networkstream = NULL;
// Private binaryreader reader;
Private binarywriter writer;
// Connect to the server
Private void btnstartconnect_click (Object sender, eventargs E)
{
Tcpclient = new tcpclient ();
Tcpclient. Connect (IP, Port );
Networkstream = tcpclient. getstream ();
}
// Send information
Private void btnstartconnect_click(Object sender, eventargs E)
{
String sendmsg = txtsendmsg. text;
Writer = new binarywriter (networkstream );
Writer. Write (sendmsg); // send information
}
// If you want to accept messages from the server.
// Reader = new binaryreader (networkstream );
// String getinfo = reader. readstring ();
}