C 回聲伺服器 5 多程序版本

2021-09-12 19:19:24 字數 2331 閱讀 3567

伺服器和客戶端都是用多程序來接收和傳送資料。

#include #include #include #include #include #include #include #include const int buf_size = 30;

void error_handling(const char *messgae);

void read_childproc(int sig);

// 接收乙個引數,ar**[1]為埠號

int main(int argc, char *argcv)

act.sa_handler = read_childproc;

sigemptyset(&act.sa_mask);

act.sa_flags = 0;

state = sigaction(sigchld, &act, 0);

server_sock = socket(pf_inet, sock_stream, 0);

memset(&server_addr, 0, sizeof(server_addr));

server_addr.sin_family = af_inet;

server_addr.sin_addr.s_addr = htonl(inaddr_any);

server_addr.sin_port = htons(atoi(argcv[1]));

if (bind(server_sock, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1)

if (listen(server_sock, 5) == -1)

while (1) else

pid = fork();

if (pid == 0)

close(client_sock);

puts("client disconnected...");

return 0;

} else

}close(server_sock);

return 0;

}

#include #include #include #include #include #include const int buf_size = 30;

void error_handling(const char *messgae);

void read_routine(int sock, char *buf);

void write_routine(int sock, char *buf);

// 接收兩個引數,ar**[1]為ip位址,ar**[2]為埠號

int main(int argc, char *ar**)

sock = socket(pf_inet, sock_stream, 0);

memset(&server_addr, 0, sizeof(server_addr));

server_addr.sin_family = af_inet;

server_addr.sin_addr.s_addr = inet_addr(ar**[1]);

server_addr.sin_port = htons(atoi(ar**[2]));

if (connect(sock, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1)

pid = fork();

if (pid == 0) else

close(sock);

return 0;

}

#include #include #include #include #include #include #include const int buf_size = 30;

// 處理錯誤

void error_handling(const char *message)

// 讀取程序退出狀態

void read_childproc(int sig)

// 客戶端接收資料

void read_routine(int sock, char *buf)

buf[str_len] = 0;

printf("message from server: %s", buf);

}}// 客戶端傳送資料

void write_routine(int sock, char *buf)

write(sock, buf, strlen(buf));

}}

github

《tcp/ip網路程式設計》

C 回聲伺服器 5 多程序版本

伺服器和客戶端都是用多程序來接收和傳送資料。include include include include include include include include const int buf size 30 void error handling const char messgae voi...

C 回聲伺服器 6 多程序pipe版本伺服器

在伺服器多程序版本的基礎上,使用管道來向乙個子程序傳送接收到的資料,該子程序將接收到的資料儲存到檔案中。客戶端 不變。include include include include include include include include const int buf size 30 void ...

C 回聲伺服器 6 多程序pipe版本伺服器

在伺服器多程序版本的基礎上,使用管道來向乙個子程序傳送接收到的資料,該子程序將接收到的資料儲存到檔案中。客戶端 不變。include include include include include include include include const int buf size 30 void ...