re:lookng for winsock tcp communications example
-
Looking for c++ winsock example code that will enable the following: Allow for multiple clients each on a different machine ie different ip address to connect in. I would like to listen on the same port for all clients and also once connectivity is established be able to send and receive using this same port for each and all the connections. Currently, with the code I have written connections seem to get established and I initially receive data from the client but when I attempt to send to client I do not get any errors but the client isn't receiving my message either. Then when viewed in Wireshark I see that the messages are associated with "ezmessagesrv". Something to do with unknown caller. One question, the server socket I use to establish the bind and listen, once the accept returns successfully with the new client socket connection should I close the server socket (the one I use to do the listening) and reinitialize before attempting to listen for other client connections?
-
Looking for c++ winsock example code that will enable the following: Allow for multiple clients each on a different machine ie different ip address to connect in. I would like to listen on the same port for all clients and also once connectivity is established be able to send and receive using this same port for each and all the connections. Currently, with the code I have written connections seem to get established and I initially receive data from the client but when I attempt to send to client I do not get any errors but the client isn't receiving my message either. Then when viewed in Wireshark I see that the messages are associated with "ezmessagesrv". Something to do with unknown caller. One question, the server socket I use to establish the bind and listen, once the accept returns successfully with the new client socket connection should I close the server socket (the one I use to do the listening) and reinitialize before attempting to listen for other client connections?
Have a look at Beej's guide to networking programming[^], there are client/server examples in chapter 6. Another starting point is the Winsock Programmer's FAQ[^], it has examples in section 6. Regarding a server, the normal way would be opening a server socket, calling bind and listen and then accepting incoming client connections. You do not close the server socket, while more incoming connections are expected. Here is a code fragment (your code could look different, but the principle stays the same):
void CSocketServer::OnAccept(int nErrorCode)
{
CAsyncNetwork::OnAccept(nErrorCode);
CAsyncNetwork* pSocket = new CAsyncNetwork;
if(Accept(*pSocket))
{
m_listSockets.push_back(pSocket); //list of sockets
} else {
delete pSocket; //handle error case
}
}CSocketServer server;
server.Open();
server.Bind(4242); //listening port of server
server.Listen();Hope this helps. :) /Moak