Stanley Hargrove
Stanley Hargrove

Reputation: 13

C# Socket Server Continuously Reading

I just made a C# socket server and it works perfectly, but if I would like to make it to be able to listen the inputs the program crashes. My question is: how can I make to continuously listen after the clients commands.

Here is my code:

using System.Net;
using System.Net.Sockets;
using System.IO;

namespace mc_server
{
    class Program
    {
        private static TcpListener serverSocket;
        private static TcpClient clientSocket;
        private static StreamReader reader;
        private static StreamWriter writer;
        private static int PORT = 5000;

        static void Main(string[] args)
        {                
            Console.WriteLine(DateTime.Now.ToString() + " >> Server starting...");
            StartServer();
            Console.ReadKey(true);
            serverSocket.Stop();
        }

        private static void StartServer()
        {
            try
            {
                serverSocket = new TcpListener(IPAddress.Any, PORT);
                serverSocket.Start();
                Console.WriteLine(DateTime.Now.ToString() + " >> Server started");
                while (true)
                {
                    clientSocket = serverSocket.AcceptTcpClient();
                    reader = new StreamReader(clientSocket.GetStream());
                    writer = new StreamWriter(clientSocket.GetStream());
                    StartListening();
                }
            }
            catch (Exception e)
            {
                if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
                    Console.WriteLine(DateTime.Now.ToString() + " [ERR]: Internet connection unavailable! (" + e.ToString() + ")");
                else
                    Console.WriteLine(DateTime.Now.ToString() + " [ERR]: Server can't be started! (" + e.ToString() + ")");
            }
        }

        private static void StartListening()
        {
            try
            {
                string line; 
                //while (true)
                //{
                    line = reader.ReadLine();

                    if (line.Contains("connected"))
                    {
                        Console.WriteLine(DateTime.Now.ToString() + " >> Remote connected");
                    }
                    else if (line.Contains("get_dir"))
                    {
                        Console.WriteLine("in_get_dir");
                        foreach (string directory in     Directory.GetDirectories(path))
                        {
                            DirectoryInfo dir_name = new DirectoryInfo(directory);
                            string dirName = dir_name.Name;
                            writer.WriteLine(line);
                        }
                    }
                //}
            }
            catch (Exception e)
            {
                Console.WriteLine(DateTime.Now.ToString() + " [ERR]: " + e.ToString() + ")");
            }
        }
    }
}

Thank you so much for your help! Regards, Stanley.

Upvotes: 1

Views: 1781

Answers (2)

Naeem A. Malik
Naeem A. Malik

Reputation: 1025

You can use async/await keywords to read & write data asynchronously on the sockets. That way, your input logic will stay separate. If you use async/await, you won't have to manage threads manually.

Upvotes: 1

Adola
Adola

Reputation: 337

I just made a C# socket server and it works perfectly, but if I would like to make it to be able to listen the inputs the program crashes.

I am not sure what you meant by that, but I think you have a problem in receiving/reading the response.


serverSocket = new TcpListener(IPAddress.Any, PORT);
            serverSocket.Start();

You've created a TcpListener named 'serverSocket'. Now let's create a socket that helps us send and receive data between the server and the client. Creating a Streamwriter and Streamreader is too long and complicated. You'll have to deal with flushing, disposing, and closing them.


Here's my 3 simplified guide of using Socket to communicate:

1.) Creating a Socket:

        Socket socket = serverSocket.AcceptSocket(); // This is a                 
//synchronous function. It will not execute the next line until a client 
//connects to the server

2.) Sending data:

        socket.Send(Encoding.ASCII.GetBytes("I am sending a short text to         
the client")); // This will send the text to client. It ONLY accepts byte 
//array, therefore we have to convert it from string to byte array to be 
//able 
//to send it.

3.) Receiving/Reading Data:

        // For Receiving Text from the Client
        byte[] responseByteArray = new byte[socket.ReceiveBufferSize]; // 
//This will create a byte array to store the data. socket.ReceiveBufferSize 
//will tells us the length of the data sent in byte array (not string yet)
        int responseLength = socket.Receive(responseByteArray);  // Tells us 
//the length of the response in byte array (not string yet)
        string response = null; // We will create a variable 'response' to 
//store the final result of the conversion
        for (int i = 0; i < responseLength; i++) // Loop to convert All byte 
//from byte array to string
        {
            response = response + (char)responseByteArray[i]; // Converts 
//every single byte of character to char
        }
        Console.WriteLine(response); // Prints out the final result in 
//string

Upvotes: 1

Related Questions