【杂项01】TCP结构体通信,win服务端接收,Linux客户端发送
程序员文章站
2022-06-06 08:33:59
...
server.cpp
#include "widget.h"
#include <QApplication>
#include <iostream>
#include <winsock2.h>
#include <QThread>
#include <QDebug>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
typedef struct{
double position[3];
double speed[3];
int flag;
}data_set;
#pragma comment(lib,"ws2_32.lib")
int main(int argc, char *argv[])
{
//init
WSADATA wsaData;
WSAStartup(MAKEWORD(2,2), &wsaData);
//socket init
SOCKET server_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
//bind
sockaddr_in sock_addr;
memset(&sock_addr, 0, sizeof(sock_addr));
sock_addr.sin_family = AF_INET;
sock_addr.sin_addr.s_addr = inet_addr("192.168.1.100");
sock_addr.sin_port = htons(8000);
bind(server_sock, (SOCKADDR*)&sock_addr, sizeof(SOCKADDR));
//listen
listen(server_sock, 20);
//accept
SOCKADDR client_addr;
int nSize = sizeof(SOCKADDR);
SOCKET client_sock = accept(server_sock, (SOCKADDR*)&client_addr, &nSize);
data_set data;
char buffer[sizeof(data)];
memset(&data, 0, sizeof(data));
memset(&buffer, 0, sizeof(buffer));
while(1){
QThread::msleep(100);
//recv
int ret = recv(client_sock, buffer, sizeof(buffer), NULL);
memcpy(&data, buffer, sizeof(buffer));
qDebug()<<ret<<" have receive" << data.flag;
//printf("%d receive from client: %s\n",ret, recv_buff);
}
return 0;
}
client.cpp
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
using namespace std;
typedef struct{
double position[3];
double speed[3];
int flag;
}data_set;
int main() {
//socket
int sock = socket(AF_INET, SOCK_STREAM, 0);
//bind
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr("192.168.1.100");
server_addr.sin_port = htons(8000);
cout << "ready to connect" << endl;
//connect
int ret = connect(sock, (struct sockaddr*)&server_addr, sizeof(server_addr));
cout << ret << endl;
sleep(2);
cout << "ready to write" << endl;
data_set data;
char buffer[sizeof(data)];
memset(&buffer, 0, sizeof(buffer));
memset(&(data), 0, sizeof(data));
data.flag=123;
while(1){
//write
data.flag++;
memcpy(buffer, &(data), sizeof(data));
write(sock, buffer, sizeof(buffer));
printf("message write to server: %d\n", data.flag);
usleep(500000);
}
close(sock);
return 0;
}