开发者

TCP: is it possible to bind a socket and then /both/ connect from it and accept from it (both client and server rules)?

is it possible in any common platform - say, in Windows - to write a servient process that creates a socket, binds it to exactly one local "address:port" (fixed), and then:

  • use it to listen for incoming connections (on the specified port) while at the same time
  • use it as a client socket to connect to some other servient (having source port identical to the one it exposes to others) ?

that is (sorry for the syntax abuse):

mySocket=socket(); mySocket.bind(myaddress, 3000); mySocket.connectTo(neighbour, whateverport); // and present to others as port 3000 mySocket.listen(); // and it listens on 3000 mySocket.accept();

?

iirc, it's not even possible/advisable to try, even in the case an API wouldn't complain, but maybe it's me that is playing too much by 开发者_如何转开发the book... so I thought of asking you

thanks a lot!


No, a socket cannot be used for both listening and connecting at the same time. connect() will return a WSAEINVAL error if listen() was already called, and listen() will return a WSAEISCONN error if connect() was already called. You need to use separate sockets.


And if you could, there's be all kinds of troubles that crop up. For example, if select() returns that the socket is readable, do you do a recv() or an accept()? You want 2 sockets to play those two roles.

What advantage is there in one socket? For example, if you were hoping to do a blocking read until something interesting happens (incoming connection, incoming data), there are alternatives. In that example, you'd use select() to block on two sockets at once. The result from select() tells you which socket is ready. That tells you if you want to accept() a new connection from the one socket or recv() new data from the other socket.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜