user3605321
user3605321

Reputation: 45

C# continuous socket listening

I am trying to setup a server that continuously reads the strings that come throught a port. I have come up to some piece of code but it will only read one string and then stop. How can I modify it so that it continously reads the strings that come to that port and puts them into the textbox?

I have tried putting a "while(true)" but that would hung up my form.I am currently researching on how to make the socket listening in a backgroundWorker or Thread.

public void start_server()
    {
            _server_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _server_socket.Bind(new IPEndPoint(IPAddress.Any, 1234));
            _server_socket.Listen(0);
            _server_socket.BeginAccept(new AsyncCallback(AcceptCallback), null);
    }

    private void AcceptCallback(IAsyncResult AR)
    {
            _client_socket = _server_socket.EndAccept(AR);
            _buffer = new byte[_client_socket.ReceiveBufferSize];
                _client_socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
    }

    private void ReceiveCallback(IAsyncResult AR)
    {
            string text = Encoding.ASCII.GetString(_buffer);
            write(text);
    }

    private void write(string text)
    {
        MethodInvoker invoker = new MethodInvoker(delegate
            {
                textBox1.Text =textBox1.Text+text;
            });
        this.Invoke(invoker);
    }

Upvotes: 1

Views: 2692

Answers (1)

Matthias247
Matthias247

Reputation: 10396

You need to restart receiving after receiving the first part by calling BeginReceive again.
Additionally you are also missing EndReceive and therefore

  • have no error handling
  • can not discover whether the remote side closed.
  • don't know how many bytes you really received (can be less than _buffer.Length).

It should look like this:

private void ReceiveCallback(IAsyncResult AR)
{
        try
        {
            int bytesTransferred = resultState.Socket.EndReceive(ar);                    
            if (bytesTransferred == 0) return; // Closed
            string text = Encoding.ASCII.GetString(_buffer, 0, bytesTransferred);
            write(text);

            // Read more
            _client_socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
        }
        catch (Exception e)
        {
            // Error handling                  
        }

}

Upvotes: 3

Related Questions