我会尝试发送一个字符串,例如" hello world"对客户来说,但我只能发送"你好"的第一部分。在矢量char []中,如何发送字符串?
send(client, win, strlen(win), 0);
win是char [],可以是字符串吗?
完整的代码是:
int main(int argc, const char* argv[])
{
WSADATA wsadata;
int error = WSAStartup (0x0202, &wsadata);
if(error == 1) return 1;
std::cout << "WSA started";
SOCKET connessione;
sockaddr_in target;
target.sin_family = AF_INET;
target.sin_port = htons (9000);
target.sin_addr.s_addr = inet_addr("127.0.0.1");
target.sin_port = htons((u_short)9001);
connessione = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (connessione == INVALID_SOCKET)
{
std::cout << "Error socket";
system("pause>null");
return INVALID_SOCKET;
}
std::cout << "\nSocket create";
if(bind(connessione, (sockaddr*)&target, sizeof(target)) != 0) return 0;
if(listen(connessione, 10) != 0) return 0;
SOCKET client;
sockaddr_in from;
int fromlen = sizeof(from);
std::cout << "\nWait the client connection...";
client = accept(connessione, (sockaddr*)&from, &fromlen);
std::cout << "\nClient connect";
std::string win;
std::cout << "\n\nInsert text to send: ";
std::cin >> win;
send(client, win, strlen(win), 0);
std::cout << "\ntext send ok. FINE";
Sleep(2000);
system("pause>null");
closesocket(connessione);
closesocket(client);
WSACleanup();
return 0;
}
答案 0 :(得分:2)
转换为char数组可能是您正在寻找的内容:
send(client, win.c_str(), win.size(), 0);
同样如前所述,您应该检查返回值(以检测任何可能的错误)并记住send
和recv
并不总是发送/接收第一个上的所有数据尝试(你必须循环,直到发送/接收整个数据)。
编辑:
>>
运算符在看到分隔符(空格,换行符等)时停止读取。如果你想阅读你可以做的整行,例如:
std::getline(std::cin, win);