使用C++中的套接字通过网络发送字符串
问题描述:
我遇到了通过TCP网络发送字符串的问题,其中字符串正在发送未输入的附加字符。使用C++中的套接字通过网络发送字符串
下面是我用来发送字符串的代码。
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";
}
这里是用于接收字符串的代码。
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";
}
我在通过网络发送字符串时做错了什么?
答
发送字符串时,你几乎做错了任何事。 ch不是指向字符串字符的指针。 lengthOfBytes不是字符串字符的长度。去研究使用字符串类的基础知识。
答
const char* ch = (const char*)&input;
int lengthOfBytes = sizeof(input);
必须更正上面的代码如下:
int lengthOfBytes = input.length()+1;
char * ch = new char [lengthOfBytes ];
std::strcpy (ch, input.c_str());
答
你已经完全误解了如何从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..
我没有窗户,所以我的客户端代码可能不等同于你需要,但它可能是一些有点像这样:
接收机:
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';