When using the knowledge of the combined operation, the following example shows a simple network connection-communication between hosts, the application program is developed for the client and service end separately. Use the client to create a receiver to connect to the server, send a receiver to the client's master machine, and request a receiver to send the receiver's internal content; the receiver's master machine receives the token for self-use, and sends a confirmation token to the receiver, at the same time, it receives and displays the internal content of the client. On this basis, you can develop a chat room based on Program Statement (C!
Use the primary source code of the producer:
Public void sendmeg () // sends a message
{
Try
{
Int Port = int32.parse (textbox3.text. tostring (); // the local host
Try
{
Tcpclient = new tcpclient (textbox1.text, Port); // create a tcpclient object example}
Catch (exception le)
{
MessageBox. Show ("tcpclient error:" + Le. Message );
}
String strdateline = datetime. Now. tow.datestring () + "" + datetime. Now. tolongtimestring (); // obtain the sending end time
Netstream = tcpclient. getstream (); // get the network stream
Sw = new streamwriter (netstream); // creates a textwriter for the vertex character in the stream.
String words = textbox4.text; // The text to be sent.
String content = strdateline + words; // content to be sent
Sw. Write (content); // streams
Sw. Close (); // closes the upstream listener
Netstream. Close (); // link a network stream
Tcpclient. Close (); // The consumer uses the consumer terminal to connect
}
Catch (exception ex)
{
MessageBox. Show ("Sending Message failed! "+ Ex. Message );
}
Textbox4.text = ""; // clear
}
The main source region on the server side:
Public void startlisten () // when you want to listen to a specific port, please
{
// Receivemeg ();
Islinked = false; // tags
Try
{
Int Port = int32.parse (textbox1.text. tostring (); // The local port to be listened
Serverlistener = new tcplistener (port); // create an example of tcplistener
Serverlistener. Start (); // notify the listener
}
Catch (exception ex)
{
MessageBox. Show ("can't start server" + ex. Message );
Return;
}
Islinked = true;
While (true) // inbound unlimited cycle wait for the client to be connected
{
Try
{
Tcpclient = serverlistener. accepttcpclient (); // configure the receiver to connect to the image
Netstream = tcpclient. getstream (); // get the network stream
Sr = new streamreader (netstream); // stream generator
}
Catch (exception re)
{
MessageBox. Show (Re. Message );
}
String Buffer = "";
String received = "";
Serialized ed + = Sr. Readline (); // a row in the pipeline stream
While (received. length! = 0)
{
Buffer + = received;
Buffer + = "\ r \ n ";
// Received = "";
Written ED = Sr. Readline ();
}
Listbox1.items. Add (buffer); // display
// Relationship
Sr. Close ();
Netstream. Close ();
Tcpclient. Close ();
}
}