我目前正试图创建一个C++ TCP IP客户端,它可以向服务器发送一个特定的字符串,使服务器发回一个带有我需要使用的一些数字的字符串。
具体来说,我需要发送字符串 "getpos",而且只能是这个。
这在第一个循环中是完美的,但在第二个循环及以后的循环中则是如此。每当我试图再次发送 "getpos "时,它就会将 "getpos "与我之前从服务器收到的数字重叠起来,然后发送,比如。 "getpos20,123,24"
好像缓冲区什么的还没有清空。 我的程序在连接到Python服务器时工作得很好,但在连接到C++服务器时却不行。
我查看了有类似问题的其他人,并尝试了各种修复方法。到目前为止,没有任何工作。
Here is my current client code (on Linux):
#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <string.h>
#include <string>
int main()
// Create a socket
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1)
return 1;
// Create a hint structure for the server we're connecting with
int port = PORTHERE;
std::string ipAddress = "IPNUMBERHERE";
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(port);
inet_pton(AF_INET, ipAddress.c_str(), &hint.sin_addr);
std::cout << "listening" << std::endl;
// Connect to the server on the socket
int connectRes = connect(sock, (sockaddr*)&hint, sizeof(hint));
if (connectRes == -1)
return 1;
std::cout << "connected" << std::endl;
// While loop:
char buf[4096];
int buflen = 1024;
while(true){
// Send to server
std::string getmypos = "getpos";
int sendRes = send(sock, getmypos.c_str(), getmypos.size(), 0);
if (sendRes == -1){
std::cout << "Could not send to server! Whoops!" << std::endl;
continue;
// Wait for response
memset(buf, 0, 4096);
int bytesReceived = recv(sock, buf, buflen, 0);
if (bytesReceived == -1)
std::cout << "There was an error getting response from server" << std::endl;
// Display response
std::cout << "SERVER> " << std::string(buf, bytesReceived) << std::endl;
sleep(1);
// Close the socket