{ TcpHeartbeat=200, TcpExeCmd }; // 定义结构体 struct DataPacket { int clientSockfd; enum Choose choose; char *cmdBuf; char *returnValue; }; struct DataPacket datapacket; struct DataPacket ReceivePackets; 在c语言tcp socket通信中,datapacket结构体为write通信发送的包,ReceivePackets结构体为read发送的包,帮我写出通信部分,连接部分不用写
时间: 2024-04-11 20:33:40 浏览: 140
下面是一个简单的C语言TCP Socket通信的示例代码,其中包括了发送和接收数据的部分。请注意,这只是一个基本的示例,实际应用中可能需要根据具体需求进行修改和扩展。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
// 定义结构体
enum Choose {
TcpHeartbeat = 200,
TcpExeCmd
};
struct DataPacket {
int clientSockfd;
enum Choose choose;
char *cmdBuf;
char *returnValue;
};
int main() {
int clientSocket;
struct sockaddr_in serverAddress;
struct DataPacket datapacket, ReceivePackets;
// 创建套接字
clientSocket = socket(AF_INET, SOCK_STREAM, 0);
if (clientSocket == -1) {
perror("Failed to create socket");
exit(EXIT_FAILURE);
}
// 设置服务器地址
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(8080); // 服务器端口号
serverAddress.sin_addr.s_addr = inet_addr("127.0.0.1"); // 服务器IP地址
// 连接服务器
if (connect(clientSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress)) < 0) {
perror("Failed to connect to server");
exit(EXIT_FAILURE);
}
// 发送数据包
datapacket.clientSockfd = clientSocket;
datapacket.choose = TcpExeCmd;
datapacket.cmdBuf = "Command";
datapacket.returnValue = "";
if (send(clientSocket, &datapacket, sizeof(datapacket), 0) == -1) {
perror("Failed to send data");
exit(EXIT_FAILURE);
}
// 接收数据包
if (recv(clientSocket, &ReceivePackets, sizeof(ReceivePackets), 0) == -1) {
perror("Failed to receive data");
exit(EXIT_FAILURE);
}
// 处理接收到的数据包
printf("Received data:\n");
printf("clientSockfd: %d\n", ReceivePackets.clientSockfd);
printf("choose: %d\n", ReceivePackets.choose);
printf("cmdBuf: %s\n", ReceivePackets.cmdBuf);
printf("returnValue: %s\n", ReceivePackets.returnValue);
// 关闭套接字
close(clientSocket);
return 0;
}
```
请根据实际情况修改服务器地址、端口号和数据包内容。这段代码发送了一个`datapacket`结构体,然后接收并处理了一个`ReceivePackets`结构体。你可以根据自己的需求进行进一步的处理和扩展。
阅读全文