为啥在打印消息时名称会打印两次?
Posted
技术标签:
【中文标题】为啥在打印消息时名称会打印两次?【英文标题】:Why does the name get printed twice while printing the message?为什么在打印消息时名称会打印两次? 【发布时间】:2018-01-21 10:34:26 【问题描述】:我编写了这个 winsock 服务器。我使用 Pageant(PuTTY) 连接客户端并向服务器发送消息。程序会在消息旁边显示客户的姓名。
程序在 char ( 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;
但是当我尝试 cout (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)
【问题讨论】:
在recv
的单独调用中似乎收到了换行符。
【参考方案1】:
我怀疑你的程序收到 4 条消息:"hi"
"\n"
"test"
"\n"
。您还应该打印 bytesReceived
并且不要忘记确保打印的缓冲区正确地以 null 结尾,或者根本不将其视为以 null 结尾的字符串。
assert(bytesReceived <= 4096);
cout << "<" << host << ">[" << bytesReceived << "] ";
cout.write(buf, (bytesReceived <= 4096) ? bytesReceived : 4096);
cout << endl;
【讨论】:
【参考方案2】: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 << "]";
【讨论】:
以上是关于为啥在打印消息时名称会打印两次?的主要内容,如果未能解决你的问题,请参考以下文章