Use C # To implement TCP-based network communication (1)
Visual C #. NET networkProgramDevelopment-TCP (2)
Pushing data to a Silverlight client with sockets: Part I
The following example implements simple network communication-Dual-host interconnection, and develops applications for the client and server respectively. The client creates a connection to the server, sends a connection request connection signal to the remote host, and sends the conversation content. The remote host receives the connection from the client and sends a confirmation connection signal to the client, receive and display the client conversation content at the same time. Based on this, you can use your creativity to develop a chat room based on programming language (C!
Client mainSource code:
Public void sendmeg () // send message
{
Try
{
Int Port = int32.parse (textbox3.text. tostring (); // remote host port
Try
{
Tcpclient = new tcpclient (textbox1.text, Port); // create a tcpclient object instance}
Catch (exception le)
{
MessageBox. Show ("tcpclient error:" + Le. Message );
}
String strdateline = datetime. Now. tow.datestring () + "" + datetime. Now. tolongtimestring (); // get the client time when sending
Netstream = tcpclient. getstream (); // get the network stream
Sw = new streamwriter (netstream); // create a textwriter and write characters to the stream
String words = textbox4.text; // to be sent
String content = strdateline + words; // content to be sent
Sw. Write (content); // write stream
Sw. Close (); // close the stream writer.
Netstream. Close (); // disable network streams
Tcpclient. Close (); // close the Client Connection
}
Catch (exception ex)
{
MessageBox. Show ("Sending Message failed! "+ Ex. Message );
}
Textbox4.text = ""; // clear
}
Main server SourceCode:
Public void startlisten () // listen for user requests on specific ports
{
// Receivemeg ();
Islinked = false; // connection flag
Try
{
Int Port = int32.parse (textbox1.text. tostring (); // local port to be listened on
Serverlistener = new tcplistener (port); // create a tcplistener object instance
Serverlistener. Start (); // start the listener
}
Catch (exception ex)
{
MessageBox. Show ("can't start server" + ex. Message );
Return;
}
Islinked = true;
While (true) // enter the infinite loop and wait for the client to connect
{
Try
{
Tcpclient = serverlistener. accepttcpclient (); // create a client connection object
Netstream = tcpclient. getstream (); // get the network stream
Sr = new streamreader (netstream); // stream Reader
}
Catch (exception re)
{
MessageBox. Show (Re. Message );
}
String Buffer = "";
String received = "";
Written ed + = Sr. Readline (); // read a row in the stream
While (received. length! = 0)
{
Buffer + = received;
Buffer + = "\ r \ n ";
// Received = "";
Written ED = Sr. Readline ();
}
Listbox1.items. Add (buffer); // display
// Close
Sr. Close ();
Netstream. Close ();
Tcpclient. Close ();
}
}