2 Replies - 7529 Views - Last Post: 24 December 2010 - 11:49 AM Rate Topic: -----

#1 jammmie999   User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 117
  • Joined: 01-April 09

C# Sockets Keep Alive

Posted 24 December 2010 - 03:07 AM

Hey guys,

I am creating a small client <-> server app and when I connect to my server "telnet localhost 500" my recive code will only allow the client to enter 1 character before closing the receive connection. Any ideas why?

            Byte[] bRecive = new byte[1024];
            int i = mySocket.Receive(bRecive, bRecive.Length, 0);

            text = Encoding.ASCII.GetString(bRecive);




Thanks

Is This A Good Question/Topic? 0
  • +

Replies To: C# Sockets Keep Alive

#2 JackOfAllTrades   User is offline

  • Saucy!
  • member icon

Reputation: 6260
  • View blog
  • Posts: 24,030
  • Joined: 23-August 08

Re: C# Sockets Keep Alive

Posted 24 December 2010 - 05:16 AM

You should receive in a loop until the receive call returns 0, indicating that the client is done.

byte [] buffer = new byte[1024];
StringBuilder sb = new StringBuilder();
int bytesRead = mySocket.Receive(buffer, buffer.Length, 0)
while (bytesRead > 0)
{
    // Use the amount of data returned in this call
    sb.Append(Encoding.ASCII.GetString(buffer, 0, bytesRead);
    bytesRead = mySocket.Receive(buffer, buffer.Length, 0);
}
text = sb.ToString();


Was This Post Helpful? 0
  • +
  • -

#3 jammmie999   User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 117
  • Joined: 01-April 09

Re: C# Sockets Keep Alive

Posted 24 December 2010 - 11:49 AM

View PostJackOfAllTrades, on 24 December 2010 - 01:16 PM, said:

You should receive in a loop until the receive call returns 0, indicating that the client is done.

byte [] buffer = new byte[1024];
StringBuilder sb = new StringBuilder();
int bytesRead = mySocket.Receive(buffer, buffer.Length, 0)
while (bytesRead > 0)
{
    // Use the amount of data returned in this call
    sb.Append(Encoding.ASCII.GetString(buffer, 0, bytesRead);
    bytesRead = mySocket.Receive(buffer, buffer.Length, 0);
}
text = sb.ToString();



Thanks for the above code. I have modifiyed it to stop receving when the user presses the enter key.

            byte[] buffer = new byte[1024];
            StringBuilder sb = new StringBuilder();
            int bytesRead = mySocket.Receive(buffer, buffer.Length, 0);
            while (bytesRead > 0)
            {
                //Use the amount of data returned in this call
                if (Encoding.ASCII.GetString(buffer, 0, bytesRead) == "\r\n")
                {
                    return sb.ToString();
                }
                sb.Append(Encoding.ASCII.GetString(buffer, 0, bytesRead));
                bytesRead = mySocket.Receive(buffer, buffer.Length, 0);

            }

            return sb.ToString();




Thanks again and merry christmas
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1