I'm trying to build a client and a server in the same program. For example, user 1 sends a packet of data to user 2, user 2 after receiving the packet sends back a different packet to user 1. The problem is, after running the program neither user receives the packets.


Qt Code:
  1. #pragma comment(lib,"ws2_32.lib")
  2. #include <WinSock2.h>
  3. #include <iostream>
  4.  
  5. static char buffer[8096 + 1];
  6. char a[256] = {};
  7. char MOTD[256];
  8.  
  9. int main()
  10. {
  11. //WinSock Startup
  12. WSAData wsaData;
  13. WORD DllVersion = MAKEWORD(2, 1);
  14. if (WSAStartup(DllVersion, &wsaData) != 0) //If WSAStartup returns anything other than 0, then that means an error has occured in the WinSock Startup.
  15. {
  16. MessageBoxA(NULL, "WinSock startup failed", "Error", MB_OK | MB_ICONERROR);
  17. return 0;
  18. }
  19.  
  20.  
  21.  
  22. SOCKADDR_IN addr; //Address that we will bind our listening socket to
  23. int addrlen = sizeof(addr); //length of the address (required for accept call)
  24. addr.sin_addr.s_addr = inet_addr(INADDR_ANY); //Broadcast locally
  25. addr.sin_port = htons(1111); //Port
  26. addr.sin_family = AF_INET; //IPv4 Socket
  27.  
  28.  
  29.  
  30.  
  31.  
  32. SOCKET sListen = socket(AF_INET, SOCK_STREAM, NULL); //Create socket to listen for new connections
  33. bind(sListen, (SOCKADDR*)&addr, sizeof(addr)); //Bind the address to the socket
  34. listen(sListen, SOMAXCONN); //Places sListen socket in a state in which it is listening for an incoming connection. Note:SOMAXCONN = Socket Oustanding Max Connections
  35.  
  36. SOCKET newConnection;
  37. newConnection = accept(sListen, (SOCKADDR*)&addr, &addrlen);
  38. if (newConnection == 0){
  39. std::cout << "Failed to accept the client's connection." << std::endl;
  40. }else{
  41. std::cout << "Client Connected!" << std::endl;
  42. }
  43.  
  44.  
  45.  
  46. for( int i=0;i< 10;i++ ){
  47. if (connect(newConnection, (SOCKADDR*)&addr, sizeof(addr)) != 0) //If we are unable to connect...
  48. {
  49. MessageBoxA(NULL, "Failed to Connect", "Error", MB_OK | MB_ICONERROR);
  50. std::cout << WSAGetLastError();
  51.  
  52. }else{
  53. std::cout << 123;
  54. }
  55. }
  56.  
  57.  
  58.  
  59. while (true){
  60.  
  61. std::cin >> a;
  62. send(newConnection, a, sizeof(a), NULL);
  63.  
  64.  
  65. recv(newConnection, MOTD, sizeof(MOTD), NULL);
  66. std::cout << "MOTD:" << MOTD << std::endl;
  67. }
  68.  
  69. system("pause");
  70. return 0;
  71. }
To copy to clipboard, switch view to plain text mode