Mega Code Archive

 
Categories / C# Book / 08 Net
 

0606 Your own server

The client speaks first, saying "Hello," and then the server responds by saying "Hello right back!" using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; class TcpDemo { static void Main() { new Thread(Server).Start(); // Run server method concurrently. Thread.Sleep (500); // Give server time to start. Client(); } static void Client() { using (TcpClient client = new TcpClient("localhost", 99)) using (NetworkStream n = client.GetStream()) { BinaryWriter w = new BinaryWriter(n); w.Write("Hello"); w.Flush(); Console.WriteLine(new BinaryReader(n).ReadString()); } } static void Server() // Handles a single client request, then exits. { TcpListener listener = new TcpListener(IPAddress.Any, 99); listener.Start(); using (TcpClient c = listener.AcceptTcpClient()) using (NetworkStream n = c.GetStream()) { string msg = new BinaryReader(n).ReadString(); BinaryWriter w = new BinaryWriter(n); w.Write(msg + " right back!"); w.Flush(); } listener.Stop(); } }