c++ - 为什么在打印消息时名称会打印两次?

标签 c++ sockets printing winsock

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

程序在字符 ( host ) 中获取客户端的信息。

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

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

                                      Test Server

>> DESKTOP-MTPOE72 connected of port 50620

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

Client disconnected (DESKTOP-MTPOE72)

最佳答案

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

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

关于c++ - 为什么在打印消息时名称会打印两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48365843/

相关文章:

css - 为屏幕和打印媒体设计页面 - 字体大小

html - 边框底部不工作打印预览 firefox css

c++ - 是否保证不会对 if 语句进行不必要的评估?

python - 如何让 Django 在 XAMPP 中与 MySQL 一起工作?

javascript - 如何在不编码或保存数据的情况下将二进制数据从 javascript 传递到 actionscript(网页到 flash)?

C UDP组播接收包丢失

python - 阻止命令运行

C++ 类设计 "helper functions"

c# - 免费的密码学库

c++ - 在 c++ .h 文件中定义和声明函数/方法