C ++套接字客户端/服务器服务器不响应客户端

时间:2014-03-20 14:06:42

标签: c++ sockets

我是套接字编程的初学者,我的客户端/服务器程序有问题,客户端无法连接到服务器。我不知道为什么,请帮忙。我想罚款问题在哪里。

服务器:

#include <iostream>
#include <windows.h>
#include <cstdlib>
#include <stdlib.h>
#include <winsock2.h>
#include <conio.h>
#include <stdio.h>

using namespace std;

int main(int argc, char* argv[])
{
   WSAData WinSockData;
   WORD Version = MAKEWORD(2,1);
   long SUCESSFUL;

   SUCESSFUL = WSAStartup(Version,&WinSockData);

    SOCKADDR_IN ADDRESS;
    int AdresSize = sizeof(ADDRESS);

   SOCKET sock_LISTEN;
   SOCKET sock_CONNECT;

   sock_CONNECT = socket(AF_INET,SOCK_STREAM,NULL);
   ADDRESS.sin_addr.s_addr = inet_addr("127.0.0.1");
   ADDRESS.sin_family = AF_INET;
   ADDRESS.sin_port = htons(27015);

    sock_LISTEN = socket(AF_INET,SOCK_STREAM,NULL);
    bind(sock_LISTEN,(SOCKADDR*)&ADDRESS,sizeof(ADDRESS));

   for(;;)
   {
       listen(sock_LISTEN,SOMAXCONN);
        cout << "Waiting for connections..." << endl;

       if(sock_CONNECT = accept(sock_LISTEN,(SOCKADDR*)&ADDRESS,&AdresSize))
       {

        cout << "Conection was found" << endl;

        SUCESSFUL = send(sock_CONNECT,"Hello",5,NULL);
       }
   }

   return 0;
}

客户端:

#include <iostream>
#include <windows.h>
#include <cstdlib>
#include <stdlib.h>
#include <winsock2.h>
#include <conio.h>
#include <stdio.h>

using namespace std;

int main(int argc, char* argv[])
{
   WSAData WinSockData;
   WORD DLLVersion;
   DLLVersion = MAKEWORD(2,1);
   long SUCESSFUL;
   SUCESSFUL = WSAStartup(DLLVersion,&WinSockData);

   string RESPONSE;
   string CONVERTER;
   char MESSAGE[200];

   SOCKADDR_IN ADDRESS;

   SOCKET sock;
   sock = socket(AF_INET,SOCK_STREAM,NULL);

   ADDRESS.sin_addr.s_addr = inet_addr("127.0.0.1");
   ADDRESS.sin_family = AF_INET;
   ADDRESS.sin_port = htonl(27015);

   cout << "Do You want to connect to this server (Y/N)" << endl;
   cin >> RESPONSE;

   RESPONSE[0] = tolower(RESPONSE[0]);

   if(RESPONSE == "n")
   {
       cout << "Quiting" <<endl;

   }else if (RESPONSE == "y")
   {
        connect(sock,(SOCKADDR*)&ADDRESS,sizeof(ADDRESS));

        SUCESSFUL = recv(sock,MESSAGE,sizeof(MESSAGE),NULL);

        CONVERTER = MESSAGE;

       cout << CONVERTER << endl;
   }else
   {
       cout << "Illegal response" <<endl;
   }
   return 0;
}

1 个答案:

答案 0 :(得分:0)

这看起来很奇怪

ADDRESS.sin_port = htons(27015);

这看起来更奇怪

ADDRESS.sin_port = htonl(27015);

两者都使用htons。

如果这不起作用,请写下

ADDRESS.sin_port = 27015;