使用C++中的套接字通过网络发送字符串

The*_*sus 1 c++ sockets networking tcp

我遇到通过TCP网络发送字符串的问题,其中字符串正在发送未输入的其他字符.

例如,当我输入以下字符串时......

我在接收端得到以下结果.

下面是我用来发送字符串的代码.

string input;
printf("Please input what you want to send...\n");
printf(">");
cin >> input;

const char* ch = (const char*)&input;
int lengthOfBytes = sizeof(input);

for (int i = 0; i < lengthOfBytes; i++)
{
   n = send(socket_d, &*ch, 10, 0);
}

//Reading in characters.
if (ch == (const char*)'\r')
{
   cout << "\n";
}
Run Code Online (Sandbox Code Playgroud)

这是用于接收字符串的代码.

int n;
int count = 0;
char byte;
n = recv(socket_d, &byte, 1, 0);
if (n <= 0)
{
    if (WSAGetLastError() != WSAEWOULDBLOCK) 
    {
        cout << "Terminated " << WSAGetLastError() << "\n";
        return;
    }
}
else
{
    cout << (char) byte;
    if ((char) byte == '\r')
        cout << "\n";
}
Run Code Online (Sandbox Code Playgroud)

在网络上发送字符串时我做错了什么?

Gal*_*lik 5

您完全误解了如何从std::string对象访问字符串数据.您需要使用这些方法std::string::data()std::string::size()获取字符串数据本身,如下所示:

发件人:

std::string input;

std::cout << "Please input what you want to send...\n";
std::cout << "> ";

cin >> input;

n = send(socket_d, input.data(), input.size(), 0);

// check for errors here..
Run Code Online (Sandbox Code Playgroud)

我没有窗口,所以我的客户端代码可能与您需要的不同,但它可能有点像这样:

接收器:

std::string s;

int n;
char buf[256];

while((n = recv(socket_d, buf, sizeof(buf), 0)) > 0)
    s.append(buf, buf + n);

if(n < 0)
{
    std::err << std::strerror(errno) << '\n';
    return 1; // error
}

// use s here

std::cout << "received: " << s << '\n';
Run Code Online (Sandbox Code Playgroud)