0

bellow is my code for server, which runs successfully but small problem is, when i send data from client from twice it accepts once. e.g. if i run this server and client also togethor; first time it accepts data from client, second time when again i ping from client side it does not accept data third time when i ping from client side it accepts data, fourth time when i ping from client it does not accept data, fifth time when i ping from client it accepts data, and so on..... thanking you in advanced.

class Program
{
   //static byte[] Buffer { get; set; }
   //static Socket sck;
   static void Main(string[] args)
   {
       while (true)
       {
           Socket sck;
           sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream,      ProtocolType.Tcp);
           sck.Bind(new IPEndPoint(0, 2000));
           sck.Listen(10);
           Socket accepted = sck.Accept();
           byte [] Buffer = new byte[accepted.SendBufferSize];
           int bytesRead = accepted.Receive(Buffer);
           byte[] formatted = new byte[30];
           for (int i = 0; i < 30; i++)
           {
               formatted[i] = Buffer[i];
           }
           string strData = Encoding.ASCII.GetString(formatted);
           Console.Write(strData + "\r\n");
           sck.Close();
           accepted.Close();
       }
   }
}
9
  • sorry, I forgot to mention that I just need only to receive data from client I dont want to send any kind of information to Client. Commented Oct 27, 2011 at 23:46
  • Does the 2nd attempt actually connect to the socket? Socket.Receive may not return any bytes or enough bytes, you should check the return value for the number of bytes actually read. Commented Oct 27, 2011 at 23:51
  • Have you tried stepping though the code, where does it actually fail? Commented Oct 27, 2011 at 23:53
  • it works perfect..the buffer is enough large to hold the data sent by Client. When I put some break points(e.g. at this position int bytesRead = accepted.Receive(Buffer);) I flows through the while loop and waits at the line "Socket accepted = sck.Accept();" Commented Oct 27, 2011 at 23:56
  • So what actually goes wrong? Does the 2nd Listen call return ok? Does the 2nd Accept call return ok? If they do then the client has connected to the server the 2nd time, but the server fails to receive data from the client. Commented Oct 28, 2011 at 0:00

3 Answers 3

1

This is not how you normally code a server. Usually, the listener stays up and just accepts new connections and closes them when done. It's possible that on the second attempt the client connects to your old listener just before you close it. Try keeping the listener open or else close the listener as soon as you accept a connection.

Sign up to request clarification or add additional context in comments.

2 Comments

if I commented the line closing socket [ (e.g. // sck.Close(); ] ; for the first ping it works but after showing data on console it flows through the while loop and comes on a line "sck.Bind(new IPEndPoint(0, 2000));" and gives me an error "Only one usage of each socket address (protocol/network address/port) is normally permitted"
Right - you have to take all the logic for the listening socket out of your loop.
0

You need a TcpListner

http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener(v=vs.71).aspx

Also, to handle many requests you need the server the process multiple requests on different threads. You'll need a thread pool. Look at ThreadPool.QueueUserWorkitem.

Here's a more complete C# TCP server example using that:

http://www.codeproject.com/KB/IP/dotnettcp.aspx

1 Comment

it seems like this one at MSDN will work...Thank you everyone over here.. :)
0

You need run the server into Thread

 public void StartListener()
        {

            while (true)
            {
                mySocket = myListener.AcceptSocket();
                Console.WriteLine("\r\nsocket type = {0}", mySocket.SocketType);
                if (mySocket.Connected)
                {
                 byte[] receive = new byte[1024];
                 mySocket.Receive(receive, 1024, 0);
                 string sBuffer = Encoding.ASCII.GetString(receive);
                }
           }
   }

Then:

        IPAddress IPaddress = Dns.Resolve(Dns.GetHostName()).AddressList[0];
        TcpListener myListener = new TcpListener(IPaddress, 50);
        myListener.Start();
        Thread th = new Thread(new ThreadStart(StartListener));
        th.Start();

More info:

TcpListener Class

Thread

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.