客户端/服务器连接错误

时间:2012-01-16 07:03:16

标签: c++ visual-c++ client-server

我试图创建一个客户端/服务器聊天,但当我运行“客户端”程序时,它无法连接到服务器,我一直在尝试,但我找不到错误 这是服务器代码:

#pragma comment(lib, "ws2_32.lib");
#include <sdkddkver.h>
#include <conio.h>
#include <stdio.h>
#include <WinSock2.h>
#include <Windows.h>
#include <iostream>

#include "wind.h"

using namespace std;

//begi
void main()
{
    long answer ;
    WSAData wsaData;
    WORD DLLVERSION;
    DLLVERSION = MAKEWORD(2,1);

    answer = WSAStartup(DLLVERSION, &wsaData);

    SOCKADDR_IN addr;
    int addrlen = sizeof(addr);

 SOCKET slisten;
 SOCKET  sConnect;

 sConnect = socket(AF_INET,SOCK_STREAM,NULL);

 addr.sin_addr.s_addr = inet_addr("127.0.0.1");
 addr.sin_family = AF_INET;

 addr.sin_port = htons(1234);

 slisten = socket(AF_INET,SOCK_STREAM,NULL);

 bind(slisten, (SOCKADDR*)&addr, sizeof(addr));
 // unlimited clients
 listen(slisten, SOMAXCONN);

 //conditions
 for(;;)

{
cout <<"waiting for client" <<endl;
if (sConnect = accept(slisten,(SOCKADDR*)&addr, &addrlen))
      {
          cout<<" A connection was found" <<endl;

           answer = send(sConnect,       "YourMessage", 12 ,NULL);
      }

 }
}

这是客户代码:

#pragma once
#pragma comment(lib, "Ws2_32.lib")
#include <sdkddkver.h>
#include <WinSock2.h>
#include <Windows.h>
#include <iostream>
#include <string>

#include "clnt.h"

using namespace std;

void main ()
{
 string confirm;
 char message[200];
  string strmessage;

long answer;
WSAData wsaData;
WORD DLLVersion;
DLLVersion = MAKEWORD(2,1);
answer = WSAStartup(DLLVersion, &wsaData);



SOCKADDR_IN addr;
 int addrlen = sizeof(addr);

  SOCKET sconnect;

  sconnect = socket(AF_INET,      SOCK_STREAM,NULL);

  addr.sin_addr.s_addr = inet_addr("127.0.0.1");

  addr.sin_family = AF_INET;

  addr.sin_port = htons(1234);


cout <<" Do you want to connect to your server?[Y/N]" <<endl;
cin>> confirm;
if(confirm == "N")
{
      exit(1);
    }
       else
    {
        if(confirm == "Y")
        {
           connect(sconnect,     (SOCKADDR*)&addr, sizeof(addr));
          answer = recv(sconnect, message, sizeof(message), NULL);
          strmessage = message;
          cout << strmessage <<endl;
          getchar();
        }

     }

getchar();
}

0 个答案:

没有答案