帮我用c++写一个tcp数据包传输接收的代码
时间: 2023-03-30 16:02:53 浏览: 102
c++编程TCP的发送与接收
4星 · 用户满意度95%
好的,以下是一个简单的 TCP 数据包传输接收的代码示例:
// 服务器端代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8888
#define MAXLINE 1024
int main() {
int sockfd;
struct sockaddr_in servaddr, cliaddr;
char buf[MAXLINE];
int n, len;
sockfd = socket(AF_INET, SOCK_STREAM, );
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
listen(sockfd, 10);
printf("等待客户端连接...\n");
len = sizeof(cliaddr);
int connfd = accept(sockfd, (struct sockaddr *)&cliaddr, &len);
printf("客户端已连接\n");
while (1) {
n = recv(connfd, buf, MAXLINE, );
if (n <= ) {
printf("客户端已断开连接\n");
break;
}
printf("接收到数据:%s\n", buf);
send(connfd, buf, n, );
}
close(connfd);
close(sockfd);
return ;
}
// 客户端代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8888
#define MAXLINE 1024
int main() {
int sockfd;
struct sockaddr_in servaddr;
char buf[MAXLINE];
int n;
sockfd = socket(AF_INET, SOCK_STREAM, );
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
inet_pton(AF_INET, "127...1", &servaddr.sin_addr);
connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
while (fgets(buf, MAXLINE, stdin) != NULL) {
send(sockfd, buf, strlen(buf), );
n = recv(sockfd, buf, MAXLINE, );
if (n <= ) {
printf("与服务器断开连接\n");
break;
}
printf("接收到数据:%s\n", buf);
}
close(sockfd);
return ;
}
阅读全文