joe_coolish
joe_coolish

Reputation: 7259

C# Socket connection error

I'm working with sockets in C# and I'm getting the following error:

A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied

Here is the code that I'm executing:

    private void HostSubscriberService()
    {
        IPAddress ipV4 = PublisherService.ReturnMachineIP();

        var localEP = new IPEndPoint(ipV4, _port);
        var server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        server.Bind(localEP);

        StartListening(server);
    }

    private void StartListening(Socket server)
    {
        EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
        while (true)
        {
            var data = new byte[1024];
            int recv = server.ReceiveFrom(data, ref remoteEP);
            string messageSendFromClient = Encoding.ASCII.GetString(data, 0, recv);

            MessageBox.Show(messageSendFromClient);
        }
    }

The error happens @ int recv = server.ReceiveFrom(data, ref remoteEP);

I just need to listen for new incoming connections and then print the message that was sent from the new client.

I need it to work on the TCP protocol, because some of the messages will be > 1500 bytes

Thanks!

Upvotes: 1

Views: 3430

Answers (2)

codymanix
codymanix

Reputation: 29468

ReceiveFrom() is for UDP, use Accept() and Receive() for TCP

Upvotes: 1

NKCSS
NKCSS

Reputation: 2746

You need to .BeginAccept() before you can receive.

Here's a link with a sinple Asynchronous Socket Server example

Upvotes: 2

Related Questions