using System; using System.Net; using System.Net.Sockets; using System.Collections.Generic; using System.Text; namespace SimpleTcpSrvr { class SimpleTcpSrvr { static void Main(string[] args) { // Define variables int recv; byte[] data = new byte[1024]; IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050); // Create a socket Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Bind the socket to the endpoint newsock.Bind(ipep); // List for up to 10 connections newsock.Listen(10); // Display a status message Console.WriteLine("Waiting for a client..."); // Create a socket for the client Socket client = newsock.Accept(); // Create an endpoint for the client IPEndPoint clientep = (IPEndPoint) client.RemoteEndPoint; // Display client connection information Console.WriteLine("Connected with [0] at port [1]", clientep.Address, clientep.Port); // Format the welcome text string welcome = "Welcome to my test server"; // Convert the welcome text to a byte array data = Encoding.ASCII.GetBytes(welcome); // Send the message to the client client.Send(data, data.Length, SocketFlags.None); // Loop while (true) { // Reformat the byte array data = new byte[1024]; // Read in data from the client recv = client.Receive(data); // If a zero was received, then exit if (recv == 0) break; // Write out the client data Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); // Echo the data back to the client client.Send(data, recv, SocketFlags.None); } // Display a disconnect message Console.WriteLine("Disconnected from [0]", clientep.Address); // Close the connections client.Close(); newsock.Close(); } } }