using System; using System.Net; using System.Net.Sockets; using System.Threading; using System.IO; using System.Collections.Generic; using System.Text; namespace TCP_Server { public class Server { // Initiate Thread Variable public Thread TCP_Thread; // Start a threaded tcp server public void Threaded_Server() { try { // Start the TCP Listener Thread TCP_Thread = new Thread(new ThreadStart(TCP_Server)); TCP_Thread.Start(); } catch (Exception e) { // Error Console.WriteLine("A TCP exception error has occured : "+ e.ToString()); TCP_Thread.Abort(); } } // The program's main entry point static void Main(string[] args) { Server TCP_Server = new Server(); } // Method that is called to do a request on the server static void doRequest(NetworkStream socketStream) { // Initiate Variables string receivedData; string separater = "#"; int separaterFound; string[] splitData; string selectQuery; string updateQuery; // Create Stream Reader & Wrtiter StreamReader sr = new StreamReader(socketStream); StreamWriter sw = new StreamWriter(socketStream); // Get data from connected client receivedData = sr.ReadLine(); // Process received data separaterFound = receivedData.IndexOf(separater); if (separaterFound >= 1) { // Workout the Select and Update Query splitData = receivedData.Split(new Char[] { char.Parse(separater) }); selectQuery = splitData[0].ToString(); updateQuery = splitData[1].ToString(); // Send data to client sw.WriteLine("Select Query : " + selectQuery); sw.WriteLine("Update Query : " + updateQuery); } else { // Wrokout the Select Query selectQuery = receivedData; // Send data to client sw.WriteLine("Select Query : " + selectQuery); } // Flush data to client sw.Flush(); } // Method that is called by threadding method to create a TCP Server Listener public void TCP_Server() { // Initiate Variables TcpListener listener; Socket connection; NetworkStream socketStream; string localIP = "127.0.0.1"; int localPort = 43; // Try to start server try { // Start Server listener = new TcpListener(IPAddress.Parse(localIP), localPort); listener.Start(); // Output to server window Console.WriteLine("Server Successfully Started"); Console.WriteLine("Operating under local end point (ip:port) " + listener.LocalEndpoint); Console.WriteLine(); Console.WriteLine("Waiting for a connection ..."); Console.WriteLine(); while (true) { connection = listener.AcceptSocket(); DateTime CurrTime = DateTime.Now; Console.WriteLine("Connection accepted from " + connection.RemoteEndPoint + " on {0:F}", CurrTime); socketStream = new NetworkStream(connection); // Do a request doRequest(socketStream); socketStream.Close(); connection.Close(); } } catch (Exception e) { // Error Console.WriteLine("Could Not Start Server : " + e.ToString()); } } } }