C # Socket ports ports

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

I'm going to keep it as simple as possible, so I'll post some code snippets so you can get the general idea. (By the way, I'm not a C # guru, this is my first socket project, so please understand my novelty)

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 the stream that listens for incoming data (smt like this):

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

      

In my opinion, the client is listening to whatever the server is sending it from port 1000. Hopefully I'm still right because this is how the chat client works.

Okay, after that I created another socket server on the server that binds to port 1001:

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

      

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

Ok, so far (hopefully), after that I create another thread that listens for data coming from the server on port 1001. So now when I send a message from port 1001, the thread listening on port 1000 gets it than if I send another message, then another thread listening on port 1001 will receive it and the other will not, and so on, it goes from one to the other.

Any idea why this is happening and how to fix it? thanks in advance.

+2


source to share


2 answers


It looks like you are confusing your ports. The port you are using to send the message is irrelevant. The second parameter SendTo

defines which port the message is sent to. This should match the port the client is listening on.



+3


source


A Socket can only accept messages intended for the port to which the socket is bound. To do this using the Bind () method.



The IPEndPoint you pass to ReceiveFrom () is only intended to store the remote address from which the message was received. It does not filter from which ports / addresses to receive data.

+1


source







All Articles