Click here to Skip to main content
15,885,662 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am new to C# having spent many years with VB and I'm trying to setup a simple client/Server communication. Th initial socket connection appears to work perfectly however, after the first connection has been setup, the client drops the connection so no more communication can occur.

Server Code
C#
<pre>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace Server
{
    class Server
    {
        static void Main(string[] args)
        {
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            IPEndPoint ipLocal = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8221);
            s.Bind(ipLocal);
            s.Listen(4);

            Console.WriteLine("Waiting for client ...\n");
            
            Socket newConnection = s.Accept();
            if (newConnection != null)
            {            
                while (true)
                {
                    byte[] buffer = new byte[4096];

                    try
                    {
                        int result = newConnection.Receive(buffer);

                        if (result > 0)
                        {
                            ASCIIEncoding encoder = new ASCIIEncoding();
                            String recdMsg = encoder.GetString(buffer, 0, result);

                            byte[] array = Encoding.ASCII.GetBytes("" + recdMsg);

                            Dungeon dungeon = new Dungeon();
                            Console.WriteLine("Welcome:  " + recdMsg);
                            int bytesSent = s.Send(buffer);
                            dungeon.Init();
                        }
                    }
                    catch (System.Exception ex)
                    {
                        Console.WriteLine(ex);    	
                    }                    
                }
            }
        }
        private string v1 = "Room 0";
        private int v2 = 0;
        internal static Room Dungeon(string v1, int v2)
        {
            throw new NotImplementedException();
        }
    }
}


Client Code
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace Client
{
    class client
    {
        static void Main(string[] args)
        {
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            IPEndPoint ipLocal = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8221);
			bool connected = false;

			while (connected == false) 
			{
				try 
				{
					s.Connect (ipLocal);
					connected = true;
                    Console.Write("We are connected!\n" , 0);

                }
                catch (Exception) 
				{

                    Console.Write("Failed", 0);
                    Thread.Sleep (1000);
				}
			}

            int ID = 0;

            while (true)
            {
                String Msg = Console.ReadLine();
                ASCIIEncoding encoder = new ASCIIEncoding();
                byte[] buffer = encoder.GetBytes(Msg);
                
                String DunMessage = encoder.GetString(buffer, 0, ID);
                Console.WriteLine(DunMessage);

                try
                {
                    Console.WriteLine("Writing to server: " + Msg);
                    int bytesSent = s.Send(buffer);
                    s.Receive(buffer);
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine(ex);	
                }
                

                Thread.Sleep(1000);
            }
        }
    }
}

Can anyone please point out where I'm going wrong?
Thanks

What I have tried:

I can't find anything else to try having established a connection. It's obviously something really basic.
Posted
Updated 13-Jul-18 1:40am
v3
Comments
Nathan Minier 13-Jul-18 7:29am    
Problem one is that Socket newConnection = s.Accept(); is outside your loop, so there's no iteration there. That's why it only connects once.

There are some good C# socket examples in the .NET documentation, for example:
https://docs.microsoft.com/en-us/dotnet/framework/network-programming/synchronous-server-socket-example

1 solution

I see at least one problem:
Your client creates a buffer according to the length of the entered string and sends that. Your server uses a local buffer of size 4096 to receive and sends the content back. But it uses the Send(byte[]) overload which sends the whole array (4096) bytes. Your client calls Receive(byte[]) which stops after the buffer is full. But that buffer is very probable much smaller than 4096. As a result you would receive garbage (the remaing data from the 4096 bytes) after sending the next command.

The solution for this problem is letting the server only send the number of bytes which has been received by using the Send(byte[] buffer, Int32, SocketFlags) overload passing result for the number of bytes to be send.

The final solution (not just echoing back) should also use a pre sized array for receiving in the client to avoid overflows when the answer is longer than the request.

But the above applies only when using localhost. With remote connections it might not work anymore when the data is larger than the transport package size because additional packets might take more time to be transferred so that you only receive partial data on either side. That is why internet communicatios use "protocols" containing a field that specifies the total length so that the receiver knows how many bytes has to be received in total.
 
Share this answer
 
Comments
Penfound 13-Jul-18 9:31am    
Thank you both for your suggestions - I'm still working on the solution so can't indicate which is the best solution yet but I will be back:)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900