2

I'm new in Socket programming. I try to write an C# chat. Every time when i call this function:

    void starteServer()
    {
        try { 
            IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
            IPAddress localIpAddress = ipHostInfo.AddressList[0];
            IPEndPoint localendpoint = new IPEndPoint(localIpAddress, serverPort);

            server.Bind(localendpoint);
            server.Listen(10);
            Recive(server);

            lb_chat.Items.Add(response);
            receiveDone.WaitOne(); 
        }
        catch (Exception e)
        {
            errorHandler(e);
        }
    }

i get an System.Net.SocketException with the reason of an unconnected Socket. I think i breaks in the Recive(server)-line. This is the Recive Method:

    private static void Recive(Socket client)
    {
        try
        {
            StateObjeckt state = new StateObjeckt();
            state.workSocket = client;
            client.BeginReceive(state.buffer, 0, StateObjeckt.bufferSize, 0, new AsyncCallback(ReceiveCallback), state);
        }
        catch (Exception e)
        {
            errorHandler(e);
        }
    }
    private static void ReceiveCallback(IAsyncResult ar)
    {
        StateObjeckt state = (StateObjeckt)ar.AsyncState;
        Socket client = state.workSocket;
        int bytesRead = client.EndReceive(ar);
        if (bytesRead > 0)
        {
            state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, bytesRead));
            client.BeginReceive(state.buffer, 0, StateObjeckt.bufferSize, 0, new AsyncCallback(ReceiveCallback), state);
        }
        else
        {
            if (state.sb.Length > 1)
            {
                response = state.sb.ToString();
            }
            receiveDone.Set();
        }
    }

hopefully someone can explain me this behavior and help me fix it.

if you need the rest of the code just visit: https://gist.github.com/chrishennig/ea4b5a974fc6f9aa2bb6

Thanks in advance

1 Answer 1

1

Your problem is you are trying to read data from a listening socket, like it is the socket that is receiving data. When you Listen with a socket, it is only used for calling Accept to accept connections, and then those subsequent connected sockets are then read and written to. So, the exception is telling you that you are trying to read from a socket that isn't connected anywhere, which is correct since no sockets have yet been accepted.

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

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.