I know this is a total newb question but I'm a beginner programmer trying to learn how to work with sockets and network programming in general with C# and .Net.

I'm working on a tcp echo client and server, two separate apps which I have programmed and run side by side. They work fine except that everytime the server accepts a connection, it echos all the bytes to the client and then gets a SocketException error: <i>10060: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.</i>

Here is the code...

class TCPEchoServer
    {
        static void Main(string[] args)
        {
            const int MAX_BUFF_SIZE = 1024;
            const int BACKLOG = 5;
            const int TIMEOUT = 3000;
            const int LISTEN_PORT = 7;

            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

            server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, TIMEOUT);

            try
            {
                server.Bind(new IPEndPoint(IPAddress.Any, LISTEN_PORT));
                server.Listen(BACKLOG);
                Console.WriteLine("The server is now listening on port {0}...", LISTEN_PORT);
            }

            catch (SocketException se)
            {
                Console.WriteLine("{0}:\t{1}", se.ErrorCode, se.Message);
                server.Close();
            }


            for (; ;)
            {
                Socket client = null;
                byte[] rcvBuffer = new byte[MAX_BUFF_SIZE];
                int bytesRead = 0, totalBytes = 0;

                try
                {
                    client = server.Accept();
                    Console.WriteLine("Handling connection from {0}...", client.RemoteEndPoint);

                    while ((bytesRead = client.Receive(rcvBuffer, totalBytes, 1, SocketFlags.None)) > 0)
                    {
                        client.Send(rcvBuffer, totalBytes, 1, SocketFlags.None);
                        totalBytes += bytesRead;
                        System.Threading.Thread.Sleep(1000);
                    }

                    Console.WriteLine("Sent {0} bytes: {1}", totalBytes, Encoding.ASCII.GetString(rcvBuffer));

                    client.Close();
                }

                catch (SocketException se)
                {
                    Console.WriteLine("{0}:\t{1}", se.ErrorCode, se.Message);
                    client.Close();
                }
            }
        }
    }
class TCPEchoClient
    {
        static void Main(string[] args)
        {
            const int SEND_PORT = 7;

            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            IPEndPoint localIP = new IPEndPoint(IPAddress.Loopback, SEND_PORT);

            byte[] sendBuffer = Encoding.ASCII.GetBytes("Th");
            byte[] rcvBuffer = new byte[sendBuffer.Length];

            int bytesRead = 0, totalBytes = 0;

            try
            {
                client.Connect(localIP);
                Console.WriteLine("Connected to {0} on port {1}...", localIP.Address, localIP.Port);

                client.Send(sendBuffer, 0, sendBuffer.Length, SocketFlags.None);

                

                while ((bytesRead = client.Receive(rcvBuffer, totalBytes, rcvBuffer.Length - totalBytes, SocketFlags.None)) > 0)
                {
                    totalBytes += bytesRead;    
                }

                Console.WriteLine("Received {0} bytes: {1}", totalBytes, Encoding.ASCII.GetString(rcvBuffer));
                
                client.Close();
            }

            catch (SocketException se)
            {
                Console.WriteLine("{0}:\t{1}", se.ErrorCode, se.Message);
                client.Close();
            }
        }
    }

Any help is very appreciated....thanks

Recommended Answers

All 4 Replies

Remove line #12 in TcpEchoServer.

I actually already tried that....if I do, then it just hangs and never does anything..

Here are some changes:

1. Server

static void Main()
    {
        const int BUFSIZE = 32; 
        const int BACKLOG = 5; 
        int servPort = 7;

        Socket server = null;

        try
        {
            server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            server.Bind(new IPEndPoint(IPAddress.Any, servPort));
            server.Listen(BACKLOG);
        }
        catch (SocketException se)
        {
            Console.WriteLine(se.Message);
            return;
        }

        byte[] rcvBuffer = new byte[BUFSIZE];  
        int bytesRcvd;  

        for (; ; )
        {  

            Socket client = null;

            try
            {
                client = server.Accept();  
                Console.Write("Handling client at " + client.RemoteEndPoint + " - ");

                 
                int totalBytesEchoed = 0;
                while ((bytesRcvd = client.Receive(rcvBuffer, 0, rcvBuffer.Length,
                SocketFlags.None)) > 0)
                {
                    client.Send(rcvBuffer, 0, bytesRcvd, SocketFlags.None);
                    totalBytesEchoed += bytesRcvd;
                }
                Console.WriteLine("echoed {0} bytes.", totalBytesEchoed);
                client.Close();  
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                client.Close();
            }
        }

2. Client

static void Main()
    {
        const int SEND_PORT = 7;

        Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
        IPEndPoint localIP = new IPEndPoint(IPAddress.Loopback, SEND_PORT);

        try
        {
            client.Connect(localIP);
            Console.WriteLine("Connected to {0} on port {1}...", localIP.Address, localIP.Port);
            string readline = "";
            Console.WriteLine("type 'end' to terminate : ");
            while( (readline=Console.ReadLine())!="end")
            {
                byte[] sendBuffer;
                byte[] rcvBuffer;
                sendBuffer = Encoding.ASCII.GetBytes(readline);
                rcvBuffer = new byte[sendBuffer.Length];
                client.Send(sendBuffer, 0, sendBuffer.Length, SocketFlags.None);
                int  bytesRead = client.Receive(rcvBuffer);
                int totalBytes = 0;
                Console.WriteLine("Received {0} bytes: {1}", totalBytes, Encoding.ASCII.GetString(rcvBuffer));

            }
                client.Close();
        }
        catch (SocketException se)
        {
            Console.WriteLine("{0}:\t{1}", se.ErrorCode, se.Message);
             
        }
        Console.ReadLine();
    }

I should have made this clearer before....the server MUST send and receive 1 byte at a time, while the client just sends all bytes at once. The point is to confirm that although data is sent with one socket send command, the client will have to receive multiple times in order to get it all back...

So this updated code doesn't work for me...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.