[ Team LiB ] |
Recipe 13.9 Writing a TCP ServerProblemYou need to create a server that listens on a port for incoming requests from a TCP client. These client requests can then be processed at the server, and any responses can be sent back to the client. Recipe 13.10 shows how to write a TCP client to interact with this server. SolutionUse the TcpListener class to create a TCP-based endpoint to listen for requests from TCP based clients. RunServer initiates a one-request TCP-based server running on a given IP address and port: public static void RunServer(string address,int port) { // set up address IPAddress addr = IPAddress.Parse(address); // set up listener on that address/port TcpListener tcpListener = new TcpListener(addr,port); if(tcpListener != null) { // start it up tcpListener.Start( ); // wait for a tcp client to connect TcpClient tcpClient = tcpListener.AcceptTcpClient( ); byte [] bytes = new byte[1024]; // get the client stream NetworkStream clientStream = tcpClient.GetStream( ); StreamReader reader = new StreamReader(clientStream,Encoding.UTF8); try { string request = reader.ReadToEnd( ); // just send an acknowledgement bytes = Encoding.UTF8.GetBytes("Thanks for the message!"); clientStream.Write(bytes,0,bytes.Length); } finally { // close the reader reader.Close( ); } // stop listening tcpListener.Stop( ); } } DiscussionRunServer takes the IP address and port passed in, creates an IPAddress from the string address, and creates a TcpListener on that IPAddress and port. Once created, the TcpListener.Start method is called to start up the server. The blocking AcceptTcpClient method is called to listen for requests from TCP-based clients. Once the client connects, the request data from the client is read and a brief acknowledgment is given, and then the client stream is closed and the TcpListener is stopped using the TcpListener.Stop method. See AlsoSee the "IPAddress Class," "TcpListener Class," and "TcpClient Class" topics in the MSDN documentation. |
[ Team LiB ] |