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)
在网络上发送字符串时我做错了什么?
您完全误解了如何从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)