使用C ++中的套接字发送字符串(Winsock TCP / IP)

时间:2015-06-04 16:52:39

标签: c++ sockets tcp

我想从客户端向服务器发送带有套接字的字符串。

以下是客户的代码:

#include <iostream>
#include <winsock.h>
#include <unistd.h>

using namespace std;

int main()
{

//Load socket
WSADATA wsaData;
WSAStartup(0x0202, &wsaData);

//Create first socket
int thisSocket;
struct sockaddr_in destination;

destination.sin_family = AF_INET;
thisSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (thisSocket < 0)
{
    cout << "Socket Creation FAILED!" << endl;
    return 0;
}

//Connect to a host
destination.sin_port = htons(13374);
destination.sin_addr.s_addr = inet_addr("127.0.0.1");
if (connect(thisSocket,(struct sockaddr *)&destination,sizeof(destination))!=0){
    cout << "Socket Connection FAILED!" << endl;
    if (thisSocket) close(thisSocket);
    return 0;
}
cout << "Connected!" << endl;

//Send the socket
//char *buffer = "Hello, this is a socket!";
string buffer = "Hello, this is a socket!";
//send(thisSocket, buffer, (int)strlen(buffer), 0);
send(thisSocket, buffer.c_str(), buffer.length(), 0);

//Close the socket
closesocket(thisSocket);
WSACleanup();

}

这是服务器的代码:

#include <iostream>
#include <winsock.h>
#include <unistd.h>

using namespace std;

int main()
{

//Load the socket
WSADATA wsaData;
WSAStartup(0x0202, &wsaData);

//Create the first socket
int thisSocket;
struct sockaddr_in destination;

destination.sin_family = AF_INET;
thisSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (thisSocket < 0)
{
    cout << "Socket Creation FAILED!" << endl;
    return 0;
}

//Bind to a socket
destination.sin_port = htons (13374);
destination.sin_addr.s_addr = INADDR_ANY;
if (bind(thisSocket, (struct sockaddr *)&destination, sizeof(destination))     <0){
    cout << "Binding Socket FAILED!" << endl;
    if (thisSocket) close(thisSocket);
    return 0;
}

//Listen on a socket
cout << "Listening on 13374..." << endl;
if (listen(thisSocket, 5)<0){
    cout << "Listening on Socket FAILED!" << endl;
    if (thisSocket) close(thisSocket);
    return 0;
}

//Accept a connection
struct sockaddr_in clientAddress;
int clientSize = sizeof(clientAddress);
thisSocket= accept(thisSocket, (struct sockaddr *)&clientAddress, (int *) &clientSize);
if (thisSocket<0)
{
    cout << "Socket Connection FAILED!" << endl;
    if (thisSocket) close(thisSocket);
    return 0;
}
cout <<"Connection Established!" << endl;

//Receive the socket

char buffer[512];
int newData;
newData = recv(thisSocket, buffer, 512, 0);
cout << newData << endl;

//Close the socket
closesocket(thisSocket);
WSACleanup();

}

您可以成像,服务器将收到数字“24”。 我怎样才能获得真正的字符串?

2 个答案:

答案 0 :(得分:2)

recv读取的数据最终会出现在buffer中。 recv函数返回收到的字节数,如果连接关闭则返回0,如果有错误则返回负值。

阅读recv reference会告诉你所有这些以及更多。

请注意,数据不会像字符串一样终止。将其作为字符串终止,如

buffer[newData] = '\0';

检查recv函数实际收到的内容后。或者您可以直接构造std::string对象:

std::string receivedString{buffer, newData};

除非recv函数实际收到了某些内容,否则也不要这样做。

答案 1 :(得分:0)

而不是:

cout << newData << endl;

做的:

cout << buffer << endl;

recv函数返回读取的字节数,缓冲区保存读取的字节数。