开发者

C# Socket server Ports

开发者 https://www.devze.com 2022-12-08 12:03 出处:网络
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 g

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 clie开发者_Go百科nt 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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消