views:

434

answers:

2

Hey, so I'm trying to build a simple lan game using sockets (not tcpclient or tcplistener, and yes I know they are the same thing). I managed to get the chat working, and now I'm trying to get the game to work. I read somewhere that the best way to manage the game data would be through another port on the server (if anyone can suggest a better way, feel free to do so).

I'm going to be as straightforward as possible, so I will post some code snippets so you can get the general idea. (btw I'm not a c# guru, it's my first socket project so please understand my newbiness)

the server is initialized like this:

sv = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
ip = new IPEndPoint(IPAddress.Parse(b.ToString()), 1000);
sv.Bind(ip);

(b is my local ip)

messages are sent using sv.SendTo();

now on the client I have:

svIp = new IPEndPoint(IPAddress.Parse(txtIp.Text.Trim()), 1000);

and a thread that listens for incoming data (smt like this):

rcv = sv.ReceiveFrom(data, ref svIp);

From my understanding, the client is listening for everything that the server sends to it from the port 1000. I hope I'm right so far, because this is how the chat client seems to work.

Ok, after that, I created on the server another socket server which is binded to port 1001:

gameIp = new IPEndPoint(IPAddress.Parse(b.ToString()), 1001);

now I want to send a message from the new socket server, let's call it gameSv, so I send a message towards a client using gameSv.SendTo(); that should ,from what I understand send, a message from port 1001, which the client shouldn't be able to receive because he's only listening for data coming from port 1000.

Ok, good so far(i hope), after this I create another thread, which listens for data coming from the server on port 1001. So now when I send a message from port 1001, the thread listening for port 1000 gets it, than if I send another message the other thread listening for port 1001 gets it and the other doesn't, and so on, it goes from one to the other.

Any idea why this happens and how to fix it? Thx in advance.

+1  A: 

A Socket can only receive messages targeted to the port the socket is bound to. To do this with the Bind() method.

The IPEndPoint which you pass into ReceiveFrom() is only there to save the remote address, from which the message was received. It it not to filter from which ports/addresses to receive data.

codymanix
Thanks, I guess I'm too tired to think straight, I kinda knew that ReceiveFrom uses that EndPoint to store the remote address, but I forgot. Anyway thank you for reminding me that :)
byte1918
+3  A: 

It sounds like you are confusing your ports. The port you are using to send a message doesn't matter. The 2nd parameter to SendTo determines which port the message gets sent to. This has to match the port that the client is listening on.

David
Thank you for your answer, I understand now where I was going wrong.
byte1918