#include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <unistd.h> #define PORT 8888 int main() { int sockfd; sockfd = socket(AF_INET, SOCK_STREAM, 0); if(sockfd == -1) { return -1; } struct sockaddr_in addr; bzero(&addr, sizeof(addr)); //清空 addr.sin_family = AF_INET; addr.sin_port = htons(PORT); addr.sin_addr.s_addr = htonl(INADDR_ANY); //与PORT端口进行绑定 if(bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) == -1) { return -1; } //监听PORT端口,并设置最大监听个数为5 if(listen(sockfd, 5) == -1) { return -1; } int clientSockfd; struct sockaddr_in clientAddr; socklen_t clientAddrSize = sizeof(struct sockaddr_in); //接受连接请求 if((clientSockfd = accept(sockfd, (struct sockaddr *)&clientAddr, &clientAddrSize)) == -1) { return -1; } else { char data[100]; //接收客户端传来的数据,并打印出来(提示:换行打印) //同时将接收到的数据原样发送给客户端 /********** BEGIN **********/ /********** END **********/ } close(clientSockfd); close(sockfd); return 0; }补全main函数中代码,实现服务器与客户端间的数据传送功能。 将客户端发来的数据完全打印出来(提示:换行打印),并且将接收到的数据原样发送给客户端。
时间: 2023-08-14 19:03:30 浏览: 110
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#define PORT 8888
int main()
{
int sockfd;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd == -1)
{
return -1;
}
struct sockaddr_in addr;
bzero(&addr, sizeof(addr)); //清空
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
//与PORT端口进行绑定
if(bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) == -1)
{
return -1;
}
//监听PORT端口,并设置最大监听个数为5
if(listen(sockfd, 5) == -1)
{
return -1;
}
int clientSockfd;
struct sockaddr_in clientAddr;
socklen_t clientAddrSize = sizeof(struct sockaddr_in);
//接受连接请求
if((clientSockfd = accept(sockfd, (struct sockaddr *)&clientAddr, &clientAddrSize)) == -1)
{
return -1;
}
else
{
char data[100];
//接收客户端传来的数据,并打印出来(提示:换行打印)
//同时将接收到的数据原样发送给客户端
/********** BEGIN **********/
int len = recv(clientSockfd, data, sizeof(data), 0);
if(len > 0) {
// 打印客户端传来的数据
printf("Received: %s\n", data);
// 发送数据给客户端
send(clientSockfd, data, len, 0);
}
/********** END **********/
}
close(clientSockfd);
close(sockfd);
return 0;
}
阅读全文