工程實訓一週作業
程式的功能是將伺服器採用fork去處理客戶端,實現多個客戶端向一臺伺服器傳送資訊,然後伺服器端接收到後再將該資訊反送給傳送者原有的客戶端。
執行結果如下
程式碼如下
//server.c
#include <sys/stat.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <fcntl.h>
#define PORT 8899
#define BACKLOG 10
void handler(int sig)
{
pid_t pid;
if ((pid = wait(NULL))<0)
{
printf(“wait failed\n”);
exit(-1);
}
printf(“the child is termino %d\n”, pid);
}
int main(int argc, char argv)
{
int server_fd;
if ((server_fd = socket(PF_INET, SOCK_STREAM, 0)) < 0)
{
perror(“socket failed”);
exit(-1);
}
struct sockaddr_in local_addr;
memset(&local_addr, 0, sizeof(struct sockaddr_in));
local_addr.sin_family = AF_INET;
local_addr.sin_addr.s_addr = htons(INADDR_ANY);
local_addr.sin_port = htons(PORT);
if (bind(server_fd, (struct sockaddr)&local_addr, sizeof(struct sockaddr)) < 0)
{
perror(“bind failed”);
exit(-1);
}
if (listen(server_fd, BACKLOG) < 0)
{
perror(“listen failed”);
exit(-1);
}
signal(SIGCHLD, handler);
pid_t pid;
struct sockaddr_in peer_addr;
socklen_t len = sizeof(peer_addr);
int connected_fd;
while(1)
{
if ((connected_fd = accept(server_fd, (struct sockaddr)&peer_addr, &len)) < 0)
{
perror(“accept failed”);
}
printf(“accept access\n”);
pid = fork();
if (pid < 0)
{
perror(“fork failed”);
exit(-1);
}
else if (pid == 0)
{
close(server_fd);
char buf[1024];
int ret_r;
while (1)
{
if ((ret_r = read(connected_fd, buf, sizeof(buf))) < 0)
{
perror(“111 read failed”);
}
printf(“buf : %s\n”, buf);
if (write(connected_fd, buf, ret_r) < 0)
{
perror(“111 write failed”);
}
if (strcmp(buf, “bye”) == 0) { exit(0);}
}
}
else
{
close(connected_fd);
}
}
return 0;
}
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <arpa/inet.h>
#define PORT 8899
int main(int argc, char *argv)
{
int connected_fd;
if ((connected_fd = socket(PF_INET, SOCK_STREAM, 0)) < 0)
{
perror(“socket failed”);
exit(-1);
}
struct sockaddr_in peer_addr;
memset(&peer_addr, 0, sizeof(peer_addr));
peer_addr.sin_family = AF_INET;
peer_addr.sin_port = htons(PORT);
inet_pton(AF_INET, “172.0.0.01”, &peer_addr.sin_addr.s_addr);
if (connect(connected_fd, (struct sockaddr)&peer_addr, sizeof(peer_addr)) < 0)
{
perror(“connected failed”);
exit(-1);
}
char buf[1024];
char recive[1024];
int ret_r;
while (1)
{
printf(“input message : “);
scanf(”%s”, buf);
ret_r = write(connected_fd, buf, sizeof(buf));
if ((ret_r = read(connected_fd, recive, 1024)) < 0)
{
perror(“222 read failed”);
}
printf(“get the message : %s\n”, recive);
if (strcmp(recive, “bye”) == 0){exit(0);}
}
close(connected_fd);
return 0;
}