1
votes

I built an app that sends strings over TCP sockets. It works like this:
Server waits for connection -> when someone connects it reads the string if the string contains <EOG it stops else it sends a respond. The client works like this: Client trying to connect to the server -> sends string -> reads respond from server, if the respod contains <EOG> it stops.
It sends every string that i tells it to, but when i send a string that contains <EOG> it only sends 5 bytes and stops. Here is the Server code:

 static void Main(string[] args)
        {
            string messageFromClient = null;
            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            byte[] bytes = new byte[1024];
            IPAddress ipAdress = IPAddress.Parse(LocalIPAddress());
            const int PORT = 13000;
            IPEndPoint localEndPoint = new IPEndPoint(ipAdress, PORT);
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(10);
                Console.WriteLine("Wating for a connection..");
                Socket handler = listener.Accept();
                Console.WriteLine("Got a connection from {0}", handler.RemoteEndPoint.ToString());
                while (true)
                {
                    while (true)
                    {

                        bytes = new byte[1024];
                        int bytesRec = handler.Receive(bytes);
                        messageFromClient += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                        if (messageFromClient.IndexOf("<Stop>") > -1) break;
                    }
                    if (messageFromClient.Contains("<EOG>"))
                    {
                        Console.WriteLine("Text recived: {0}",messageFromClient.Replace("<Stop>",""));
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                        Console.WriteLine("Handler closed.");
                        return;
                    }
                    Console.WriteLine("Text recived: {0}", messageFromClient.Replace("<Stop>", ""));
                    messageFromClient = null;
                    string readInput = Console.ReadLine() + "<Stop>";
                    byte[] messageToClient = Encoding.ASCII.GetBytes(readInput);
                    handler.Send(messageToClient);
                    if (readInput.Contains("<EOG>"))
                    {
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                        Console.WriteLine("Handler closed.");
                        return;
                    }
                }
            }
            catch (SocketException se)
            {
                Console.WriteLine(se.ToString());
            }
            catch (ArgumentNullException ane)
            {
                Console.WriteLine(ane.ToString());
            }

        }
        public static string LocalIPAddress()
        {
            IPHostEntry host;
            string localIP = "";
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    localIP = ip.ToString();
                    break;
                }
            }
            return localIP;
        }

Here is the Client code:

static void Main(string[] args)
        {
            IPAddress ipAdress = IPAddress.Parse(LocalIPAddress());
            byte[] bytes = new byte[1024];
            const int PORT = 13000;
            IPEndPoint remoteEP = new IPEndPoint(ipAdress, PORT);
            Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            string messageFromServer = null;
            try
            {
                sender.Connect(remoteEP);
                Console.WriteLine("Connected to {0}",sender.RemoteEndPoint.ToString());
                while (true)
                {
                    string readInput = Console.ReadLine() + "<Stop>";
                    byte[] messageToServer = Encoding.ASCII.GetBytes(readInput);
                    if (readInput.Contains("<EOG>"))
                    {
                        messageToServer = Encoding.ASCII.GetBytes("<EOG>");
                        int bytesSentEnd = sender.Send(messageToServer);
                        Console.WriteLine("Sent {0} bytes to the server", bytesSentEnd);
                        sender.Shutdown(SocketShutdown.Both);
                        sender.Close();
                        Console.WriteLine("Sender closed.");
                        return;
                    }
                    int bytesSent = sender.Send(messageToServer);
                    Console.WriteLine("Sent {0} bytes to the server", bytesSent);
                    while (true)
                    {
                        int bytesRec = sender.Receive(bytes);
                        messageFromServer += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                        if (messageFromServer.IndexOf("<Stop>") > -1) break;
                        if (messageFromServer.Contains("<EOG>"))
                        {
                            sender.Shutdown(SocketShutdown.Both);
                            sender.Close();
                            Console.WriteLine("Sender closed.");
                            return;
                        }
                    }
                    Console.WriteLine("Message from server: {0}", messageFromServer.Replace("<Stop>",""));
                    messageFromServer = null;
                }
            }
            catch (SocketException se)
            {
                Console.WriteLine("Sokcet Exception: {0}", se.ToString());
            }
            catch (ArgumentNullException ane)
            {
                Console.WriteLine("Argument Null Exception: {0}", ane.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unexpected excetption: {0}",ex.ToString());
            }
        }
        public static string LocalIPAddress()
        {
            IPHostEntry host;
            string localIP = "";
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    localIP = ip.ToString();
                    break;
                }
            }
            return localIP;
        }

If the user input something like "hi <EOG> " it only sends 5 bytes and stops itself. now i dont want that to happen, i want it to send the whole message and only then stop itself. also, if the message contains "<EOG>" then the reciving side doesnt recive anything.
How can i make it send the whole message and only then shut down?

1
handler.Receive(bytes) has a bug. It overwrites previously read data from previous loop iterations. Fix that, update the code and report whether that solves the problem. - usr
It sends exactly what you tell it to send : messageToServer = Encoding.ASCII.GetBytes("<EOG>"); - jdweng

1 Answers

0
votes

I was able to fix this issue by doing what jdweng told me, and a few more tweaks to the code. here is the working code if anyone want it:
Server Side:

static void Main(string[] args)
    {

        string messageFromClient = null;
        Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        byte[] bytes = new byte[1024];
        IPAddress ipAdress = IPAddress.Parse(LocalIPAddress());
        const int PORT = 13000;
        IPEndPoint localEndPoint = new IPEndPoint(ipAdress, PORT);
        try
        {
            listener.Bind(localEndPoint);
            listener.Listen(10);
            Console.WriteLine("Wating for a connection..");
            Socket handler = listener.Accept();
            Console.WriteLine("Got a connection from {0}", handler.RemoteEndPoint.ToString());
            while (true)
            {
                while (true)
                {

                    bytes = new byte[1024];
                    int bytesRec = handler.Receive(bytes);
                    messageFromClient += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                    if (messageFromClient.IndexOf("<Stop>") > -1) break;
                }
                if (messageFromClient.Contains("<EOG>"))
                {
                    Console.WriteLine("Text recived: {0}", messageFromClient.Replace("<Stop>", ""));
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                    Console.WriteLine("Handler closed.");
                    return;
                }
                Console.WriteLine("Text recived: {0}", messageFromClient.Replace("<Stop>", ""));
                messageFromClient = null;
                string readInput = Console.ReadLine() + "<Stop>";
                byte[] messageToClient = Encoding.ASCII.GetBytes(readInput);
                handler.Send(messageToClient);
                if (readInput.Contains("<EOG>"))
                {
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                    Console.WriteLine("Handler closed.");
                    return;
                }
            }
        }
        catch (SocketException se)
        {
            Console.WriteLine(se.ToString());
        }
        catch (ArgumentNullException ane)
        {
            Console.WriteLine(ane.ToString());
        }

    }
    public static string LocalIPAddress()
    {
        IPHostEntry host;
        string localIP = "";
        host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                localIP = ip.ToString();
                break;
            }
        }
        return localIP;
    }

Client Side:

static void Main(string[] args)
    {
        IPAddress ipAdress = IPAddress.Parse(LocalIPAddress());
        byte[] bytes = new byte[1024];
        const int PORT = 13000;
        IPEndPoint remoteEP = new IPEndPoint(ipAdress, PORT);
        Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        string messageFromServer = null;
        try
        {
            sender.Connect(remoteEP);
            Console.WriteLine("Connected to {0}", sender.RemoteEndPoint.ToString());
            while (true)
            {
                string readInput = Console.ReadLine() + "<Stop>";
                byte[] messageToServer = Encoding.ASCII.GetBytes(readInput);
                if (readInput.Contains("<EOG>"))
                {
                    int bytesSentEnd = sender.Send(messageToServer);
                    Console.WriteLine("Sent {0} bytes to the server", bytesSentEnd);
                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                    Console.WriteLine("Sender closed.");
                    return;
                }
                int bytesSent = sender.Send(messageToServer);
                Console.WriteLine("Sent {0} bytes to the server", bytesSent);
                while (true)
                {
                    int bytesRec = sender.Receive(bytes);
                    messageFromServer += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                    if (messageFromServer.Contains("<EOG>"))
                    {
                        sender.Shutdown(SocketShutdown.Both);
                        sender.Close();
                        Console.WriteLine("Sender closed.");
                        return;
                    }
                    if (messageFromServer.IndexOf("<Stop>") > -1) break;
                }
                Console.WriteLine("Message from server: {0}", messageFromServer.Replace("<Stop>", ""));
                messageFromServer = null;
            }
        }

        catch (SocketException se)
        {
            Console.WriteLine("Sokcet Exception: {0}", se.ToString());
        }
        catch (ArgumentNullException ane)
        {
            Console.WriteLine("Argument Null Exception: {0}", ane.ToString());
        }
        catch (Exception ex)
        {
            Console.WriteLine("Unexpected excetption: {0}", ex.ToString());
        }
    }
    public static string LocalIPAddress()
    {
        IPHostEntry host;
        string localIP = "";
        host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                localIP = ip.ToString();
                break;
            }
        }
        return localIP;
    }

Hope this helps someone somehow :)