我一直在寻找一种使用 Winsock2 通过 Windows 套接字发送整数的方法。我已经查看了人们在 stackoverflow 上提出的大多数问题,如果不是全部的话。
这是我为客户端发送的整数:
struct struct_var
{
int Packet;
int Number;
};
struct_var *arraystruct;
arraystruct = (struct_var *) malloc(sizeof(struct_var));
(*arraystruct).Packet = 100;
(*arraystruct).Number = 150;
int bytes = send(client,(char*)arraystruct,sizeof(*arraystruct),0);`
我也尝试使用以下方式发送:
int int_data = 4;
int bytes = send(server, (char*) &int_data, sizeof(int), 0);`
这是在另一个stackoverflow问题上推荐的 这是接收方,也被推荐:
int int_data;
int bytes = recv(server, (char*) &int_data, sizeof(int), 0);
cout << int_data;`
当我运行这些时,我从命令行得到的输出是:-858993460
有谁知道为什么会这样?
我还希望它具有正确的字节顺序,因为这将通过多种计算机发送。提前感谢谁能帮助我
完整的服务器代码:
int main() {
WSADATA wsaData;
WORD version;
int error;
version = MAKEWORD(2, 0);
error = WSAStartup(version, &wsaData);
if ( error != 0 )
{
return FALSE;
}
if ( LOBYTE( wsaData.wVersion ) != 2 ||
HIBYTE( wsaData.wVersion ) != 0 )
{
WSACleanup();
return FALSE;
}
SOCKET server;
server = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons(5555);
if (bind( server, (SOCKADDR*)&sin, sizeof(sin) ) == SOCKET_ERROR ){
DWORD ec=WSAGetLastError();
cerr << hex << "bind ERROR" << ec << endl;
return FALSE;
}
if ( listen( server, SOMAXCONN ) == SOCKET_ERROR ) {
DWORD ec=WSAGetLastError();
cerr << hex << "listen ERROR" << ec << endl;
return FALSE;
}
SOCKET client;
int length;
while(1) {
if ( listen( server, SOMAXCONN ) == SOCKET_ERROR ) {
DWORD ec=WSAGetLastError();
cerr << hex << "listen ERROR" << ec << endl;
return FALSE;
}
length = sizeof sin;
client = accept( server, (SOCKADDR*)&sin, &length );
cout << "Client connected" << endl;
cout << "Sending Instructions..." << endl;
int int_data;
int bytes;
bytes = recv(client, (char*) &int_data, sizeof(int), 0);
cout << int_data << endl;
}
}
}
完整的客户代码:
int main() {
WSADATA wsaData;
WORD version;
int error;
version = MAKEWORD(2, 0);
error = WSAStartup(version, &wsaData);
if ( error != 0 )
{
return FALSE;
}
if ( LOBYTE( wsaData.wVersion ) != 2 ||
HIBYTE( wsaData.wVersion ) != 0 )
{
WSACleanup();
return FALSE;
}
SOCKET client;
client = socket( AF_INET, SOCK_STREAM, 0 );
sockaddr_in sin;
memset( &sin, 0, sizeof sin );
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = inet_addr("127.0.0.1");
sin.sin_port = htons(5555);
if ( connect(client, (SOCKADDR*)(&sin), sizeof sin ) == SOCKET_ERROR ){
return FALSE;
}
int int_data = 4;
int bytes = send(client, (char*) &int_data, sizeof(int), 0);
}