Question

This is my server code

byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);
UdpClient newsock = new UdpClient(ipep);

Console.WriteLine("Waiting for a client...");

IPEndPoint send = new IPEndPoint(IPAddress.Any, 0);

byte[] data1 = newsock.Receive(ref send);
int test1 = BitConverter.ToInt32(data1, 0);
Console.WriteLine("test1 = {0}", test1);

This is my client code

byte[] data = new byte[1024];
string stringData;
UdpClient server = new UdpClient("127.0.0.1", 9050);

IPEndPoint send = new IPEndPoint(IPAddress.Any, 0);

int test1 = 45;

byte[] data1 = BitConverter.GetBytes(test1);
server.Send(data1, data1.Length);

According to my client and server, The client is the one sending data to server.

But my requirement is other way around! and im unable to do that.. When i try adding this code to the server

byte[] buffer = ASCIIEncoding.ASCII.GetBytes("Hello Client");
newsock.Send(buffer, buffer.Length);

I get an Exception as The operation is not allowed on non-connected sockets.

Can some one help me?

Was it helpful?

Solution

Check out JoinMulticastGroup (it's like Connect for TcpClient). You need to do this prior to broadcasting (that is, if you are broadcasting).

The documentation for UdpClient will also be helpful to you.

OTHER TIPS

UDP is connectionless. When you call connect on a UDP socket, you are really just setting the default destination IP and port. The receiver on the other end has to use Socket.ReceiveFrom (called recvfrom in UNIX) to find out where the packet came from and then SendTo to reply to the original request. The server could use connect but that would be awkward if you wanted to support multiple clients.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top