为什么打印邮件时名称会被打印两次?

时间:2018-01-21 10:34:26

标签: c++ sockets printing winsock

我写了这个winsock服务器。我使用Pageant(PuTTY)连接客户端并向服务器发送消息。程序会在消息旁边显示客户端的名称。

程序在char(主机)中获取客户端的信息。

#include <iostream>
#include <iomanip>
#include <WS2tcpip.h>
#include <sstream>
#include <Windows.h>

#pragma comment (lib, "ws2_32.lib")

using namespace std;

int main() {

    // Console info
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    int columns, rows;

    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
    columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
    rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;

    // Centered welcome text
    cout << endl << setw(columns/2) << "Test Server" << endl << endl;

    // Initialize winsock
    WSADATA wsData;
    WORD ver = MAKEWORD(2, 2);

    int wsOk = WSAStartup(ver, &wsData);
    if (wsOk != 0) {
        cerr << "Can't initialize winsock! Quitting" << endl;
        system("pause>nul");
        return 0;
    }

    // Create a socket
    SOCKET listening = socket(AF_INET, SOCK_STREAM, 0);
    if (listening == INVALID_SOCKET) {
        cerr << "Can't create a socket Quitting" << endl;
        system("pause>nul");
        return 0;
    }

    // Bind the socket to an ip address and port 
    sockaddr_in hint;
    hint.sin_family = AF_INET;
    hint.sin_port = htons(54000);
    hint.sin_addr.S_un.S_addr = INADDR_ANY;

    bind(listening, (sockaddr*)&hint, sizeof(hint));

    // Tell winsock the socket is for listening
    listen(listening, SOMAXCONN);

    // Wait for connection
    sockaddr_in client;
    int clientSize = sizeof(client);

    SOCKET clientSocket = accept(listening, (sockaddr*)&client, &clientSize);

    char host[NI_MAXHOST]; // remote name of client
    char service[NI_MAXHOST]; // port of client

    ZeroMemory(host, NI_MAXHOST);
    ZeroMemory(service, NI_MAXHOST);

    if (getnameinfo((sockaddr*)&client, sizeof(client), host, NI_MAXHOST, service, NI_MAXSERV, 0) == 0) {
        cout << ">> " << host << " connected of port " << service << endl;
    } else {
        inet_ntop(AF_INET, &client.sin_addr, host, NI_MAXHOST);
        cout << ">> " <<  host << " connected on port " <<
            ntohs(client.sin_port) << endl;
    }

    string name = host;

    // Change title
    SetConsoleTitle(("Connected ("+name+")").c_str());

    // Close listening socket 
    closesocket(listening);

    // While loop: accept and echo message back to client
    char buf[4096];
    char ERRMsg[4096] = "/n Server Disconnected... /n";

    cout << endl;

    while (true) {
        ZeroMemory(buf, 4096);

        // Wait for client to send data
        int bytesReceived = recv(clientSocket, buf, 4096, 0);
        if ( bytesReceived == 0 ) {

            // Print Client disconnected on the console
            cout << endl << "Client disconnected (" << host << ")" << endl;         

            // Close socket; because the client disconnected
            closesocket(clientSocket);

            system("pause>nul");

            break;
        }

        // Display message on console
        cout << " <" << host << "> " << buf; // The problem is in this line


        // Echo message back to client
        send(clientSocket, 0, bytesReceived, 0);

    }

    // Close the socket 
    closesocket(clientSocket);

    // Cleanup winsock 
    WSACleanup();

    return 0;
}

但是当我尝试cout(主机)和存储在(buf)中的消息时,它会打印(主机)两次。这有什么问题?

                                      Test Server

>> DESKTOP-MTPOE72 connected of port 50620

 <DESKTOP-MTPOE72> hi <DESKTOP-MTPOE72>
 <DESKTOP-MTPOE72> test <DESKTOP-MTPOE72>

Client disconnected (DESKTOP-MTPOE72)

2 个答案:

答案 0 :(得分:0)

我怀疑您的计划会收到4条消息:"hi" "\n" "test" "\n"。您还应该打印bytesReceived并且不要忘记确保打印的缓冲区正确地以空值终止,或者根本不将其视为以空字符结尾的字符串。

assert(bytesReceived <= 4096);
cout << "<" << host << ">[" << bytesReceived << "] ";
cout.write(buf, (bytesReceived <= 4096) ? bytesReceived : 4096); 
cout << endl; 

答案 1 :(得分:0)

cout << " <" << host << "> " << buf;没有结束行:

<DESKTOP-MTPOE72> hi <DESKTOP-MTPOE72>
<DESKTOP-MTPOE72> test <DESKTOP-MTPOE72>

必须读作:

首次打印:

<DESKTOP-MTPOE72> hi 

第二次印刷:

<DESKTOP-MTPOE72> *end of line*

因此,您可能会收到hi然后\n等消息

要了解真正发生的事情,请尝试cout << "[ <" << host << "> " << buf << "]";