I am writing an application and I don't understand a point. I am trying to receive data from a specific client. In a TCP socket, accept returns to you an fd
number, so you can communicate over this fd
number with a specific client.
In recvfrom
, anything canno开发者_如何学Pythont specify that receive data from that client. It receives data from everyone who sent. I am trying to solve this, but I am not sure how to do this.
The second problem is that, after opening a socket, I open other socket. I send second socket number to client, and client sends second data on this second socket. In server side, the server listens to the first socket (not the second socket). But although client sends data from the second socket and the server listens to the first socket, server takes data. I print two socket as integer and see that two are different. How can the server read data that is sent on second socket, on the first socket?
Yeah, my question is a bit complicated. Basically I say:
recvfrom(sock, &client, sizeof(Client), MSG_WAITALL, (struct sockaddr *)&clientAddr2, &size);
How can tell a specific client (say client 2) to listen in the line above? (in TCP sockets, it is done by fd
number, but how it is in UDP socket?).
Accept isn't used with udp. You call socket, you call bind to establish the port, you call sendto and recvfrom.
I'm afraid that I can't follow your description very well, but I hope this helps.
TCP and UDP are distinct and not compatible protocols. UDP clients and servers talk to each other, TCP clients and servers talk to each other. Hypothetically, you could use a RAW socket to talk to TCP on the other side, but you'd have to have a complete TCP protocol implementation.
UDP has no connections. If you have a concept of different clients, you have to sort them out with data you put inside the packets.
If I understand what you are looking for, you would need to bind each socket on the server to a different port number. Then the client would need to send to the desired port.
However, it may not be necessary to do that. The server could examine the address that is supplied via the recvfrom() call and associate it with the appropriate client and process it (e.g., via a worker thread) according to which client sent it.
I don't think you can use UDP to communicate with TCP. UDP is not a super set of TCP. They are two different protocols of the same layer. For more info try this page
When you open two sockets to the same port in a computer, you are not guaranteed that both sockets will receive the data. In fact, in my experience only the first socket will.
精彩评论