客户/服务器交互

时间:2012-01-18 13:54:47

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

当我my previous question的程序响应客户端时,它应该发送加密消息 当客户端连接时,它会发送一条消息,如“YourMessage”。现在我想这样做,以便当客户端连接此消息时,应以某种方式编码,并在客户端的屏幕上显示其他内容。我该怎么做呢?

服务器代码:

#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);
         char cMyCharacter = 'A';
       int iMyAsciiValue = static_cast<int>(cMyCharacter);
      }

 }
}

客户代码:

#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();
}

1 个答案:

答案 0 :(得分:0)

它应该像现在一样工作,但不是发送明文字符串,而是发送加密字符串。如果加密使得二进制数据blob也发送它,那么客户端必须在将其显示给用户之前解密。