다중 프로세스 TCP 서버의 간단한 구현

10788 단어 인터넷
서버 쪽: 서버.c:
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define _BACKLOG_ 10

int CreateSock(char *ip, int port)
{
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if(sock < 0)
    {
        printf("socket error
"
); exit(1); } struct sockaddr_in server_addr; bzero(&server_addr, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(port); inet_pton(AF_INET, ip, &server_addr.sin_addr); if(bind(sock, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) { printf("bind error
"
); close(sock); exit(2); } if(listen(sock, _BACKLOG_) < 0) { printf("listen error
"
); close(sock); exit(3); } return sock; } void Service(int client_sock) { for(;;) { char buf[1024]; buf[0] = 0; int s = read(client_sock, buf, sizeof(buf)); if(s > 0) { buf[s-1] = 0; if(strncasecmp(buf, "quit", 4) == 0) { printf("client quit!
"
); exit(0); } printf("client:%s
"
, buf); write(client_sock, buf, strlen(buf)); } } } int main(int argc, char *argv[]) { if(argc < 3) { printf("%s [addr]:[port]
"
, argv[0]); exit(1); } int sock = CreateSock(argv[1], atoi(argv[2])); struct sockaddr_in client_addr; bzero(&client_addr, sizeof(client_addr)); while(1) { printf("wait connect!
"
); socklen_t len = 0; int client_sock = accept(sock, (struct sockaddr*)&client_addr, &len); if(client_sock < 0) { printf("accept arror
"
); continue; } char buf_ip[INET_ADDRSTRLEN]; buf_ip[0] = 0; inet_ntop(AF_INET, &client_addr, buf_ip, sizeof(buf_ip)); printf("get connect, ip is:%s, port is: %d
"
, buf_ip, ntohs(client_addr.sin_port)); pid_t pid = fork(); if(pid < 0) { printf("fork error"); continue; } else if(pid == 0) { pid_t pid = fork(); if(pid < 0) { printf("fork error"); continue; } else if(pid > 0) exit(4); } else { wait(NULL); continue; } Service(client_sock); } close(sock); return 0; }

클라이언트:client.c
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

int main(int argc, char *argv[])
{
    if(argc < 3)
    {
        printf("%s [addr]:[port]
"
, argv[0]); return 1; } int sock = socket(AF_INET, SOCK_STREAM, 0); if(sock < 0) { printf("socket error
"
); return 2; } struct sockaddr_in server_addr; bzero(&server_addr, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(atoi(argv[2])); inet_pton(AF_INET, argv[1], &server_addr.sin_addr); if(connect(sock, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) { printf("connect error
"
); close(sock); return 3; } printf("connect success!
"
); while(1) { char buf[1024]; memset(buf, 0x00, sizeof(buf)); printf("please input:>"); fflush(stdout); read(0, buf, sizeof(buf)); write(sock, buf, strlen(buf)); if(strncasecmp(buf, "quit", 4) == 0) { printf("client quit!
"
); break; } int s = read(sock, buf, sizeof(buf)); if(s > 0) { buf[s] = 0; printf("server:%s
"
, buf); } } close(sock); return 0; }

동일한 LAN에서 여러 고객이 동일한 서버에 동시에 액세스할 수 있음

좋은 웹페이지 즐겨찾기