socket 매핑 서버 - (다중 클라이언트 연결 처리 (fork), 종료 정보 표시)

8346 단어
server
#include 
#include           /* See NOTES */
#include 
#include 
#include 
#include in.h>
#include 
#include <string.h>
#include 

void do_service(int conn)
{
        char recvbuf[1024];
        while(1)
        {
                memset(recvbuf,0,sizeof(recvbuf));
                int ret = read(conn,recvbuf,sizeof(recvbuf));
                if(ret == 0)
                {
                        printf("client close
"); break; } else if (ret == -1) { printf("read failed
"); exit(1); } fputs(recvbuf,stdout); write(conn,recvbuf,ret); } } int main(void) { int listenfd; listenfd = socket(PF_INET,SOCK_STREAM,0); if(listenfd < 0) { printf("creat socket failed
"); exit(1); } struct sockaddr_in servaddr; memset(&servaddr,0,sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(5188); servaddr.sin_addr.s_addr = htonl(INADDR_ANY);//host any address int n=1; if(setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&n,sizeof(n))<0) { printf("set resueaddr failed
"); exit(1); } if(bind(listenfd,(struct sockaddr*)&servaddr,sizeof(servaddr))<0) { printf("bind fialed
"); exit(1); } if(listen(listenfd,SOMAXCONN)<0) { printf("listen failed
"); exit(1); } struct sockaddr_in peeraddr; socklen_t peerlen = sizeof(peeraddr); int conn; pid_t pid; while(1) { if((conn=accept(listenfd,(struct sockaddr*)&peeraddr,&peerlen))<0) { printf("accept failed
"); exit(1); } printf("ip=%s, port=%d
",inet_ntoa(peeraddr.sin_addr),ntohs(peeraddr. sin_port)); pid = fork(); if(pid == -1) { printf("fork failed
"); exit(1); } if (pid == 0) { close(listenfd); do_service(conn); exit(1); } else { close(conn); } } return 0; }

client 참조http://www.cnblogs.com/Malphite/p/7529200.html
다음으로 전송:https://www.cnblogs.com/Malphite/p/7530584.html

좋은 웹페이지 즐겨찾기