• 网络编程


    1. 服务器端
    #include <stdio.h>
    #include <unistd.h>
    #include <sys/socket.h>
    #include <stdlib.h>
    #include <ctype.h>
    #include <arpa/inet.h>
    #include <sys/types.h>
    #include <string.h>
    #include <strings.h>
    
    #define SERVER_PORT 6666
    #define SERVER_IP "127.0.0.1"
    
    int main()
    {
        int lfd=socket(AF_INET,SOCK_STREAM,0);
        struct sockaddr_in server_addr;
        bzero(&server_addr, sizeof(server_addr));
        server_addr.sin_family= AF_INET;
        server_addr.sin_port=htons(6666);
        server_addr.sin_addr.s_addr= htonl(INADDR_ANY);
    
        bind(lfd,(struct sockaddr*) &server_addr, sizeof(server_addr));
    
        listen(lfd,32);
        int cfd;
        struct sockaddr_in client_addr;
        socklen_t client_addr_len=sizeof(client_addr);
        cfd=accept(lfd,(struct sockaddr*) &client_addr, &client_addr_len);
        char client_ip_buf[BUFSIZ];
        inet_ntop(AF_INET,&client_addr.sin_addr.s_addr,client_ip_buf, sizeof(client_ip_buf));
        printf("client ip: %s   client port: %d
    ", client_ip_buf, ntohs(client_addr.sin_port));
        
        char buf[BUFSIZ];
        while(1){
            int n=read(cfd,buf,sizeof(buf));
            int i;
            for(i=0;i<n;i++){
                buf[i]=toupper(buf[i]);
            }
            write(cfd,buf,n);
        }
        close(lfd);
        close(cfd);
    
        return 0;
    }
    
    1. 客户端
    #include <stdio.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <arpa/inet.h>    // struct sockaddr_in
    #include <string.h>
    
    #define SERVER_IP "127.0.0.1"
    
    int main()
    {
        int cfd;
        cfd=socket(AF_INET,SOCK_STREAM,0);
        
        struct sockaddr_in server_addr;
    
        memset(&server_addr,0,sizeof(server_addr));
        server_addr.sin_family=AF_INET;
        server_addr.sin_port=htons(6666);
        inet_pton(AF_INET,SERVER_IP, &server_addr.sin_addr.s_addr);
        connect(cfd,(struct sockaddr*) &server_addr, sizeof(server_addr));
    
        char buf[BUFSIZ];
        while(1){
            fgets(buf,sizeof(buf),stdin);
            write(cfd,buf,strlen(buf));
    
            int n;
            n=read(cfd,buf,sizeof(buf));
            write(STDOUT_FILENO,buf,n);
        }
        close(cfd);
        return 0;
    }
    

    如果先关server,再关client,则下次启动server时bind会报错,Address already in use.

    关闭server后,端口并没有被释放。


    代码改进,增加错误处理函数:
    wrap.c

    #include <stdlib.h>
    #include <errno.h>
    #include <sys/socket.h>
    void perr_exit(const char *s)
    {
    	perror(s);
    	exit(1);
    }
    int Accept(int fd, struct sockaddr *sa, socklen_t *salenptr)
    {
    	int n;
    	again:
    	if ( (n = accept(fd, sa, salenptr)) < 0) {
    		if ((errno == ECONNABORTED) || (errno == EINTR))       // accept为慢速系统调用。 EINTR  The system call was interrupted by a signal that was caught before a valid connection arrived.   CONNABORTED  A connection has been aborted.
    			goto again;
    		else
    			perr_exit("accept error");
    	}
    	return n;
    }
    int Bind(int fd, const struct sockaddr *sa, socklen_t salen)
    {
    	int n;
    	if ((n = bind(fd, sa, salen)) < 0)
    		perr_exit("bind error");
    	return n;
    }
    int Connect(int fd, const struct sockaddr *sa, socklen_t salen)
    {
    	int n;
    	if ((n = connect(fd, sa, salen)) < 0)
    		perr_exit("connect error");
    	return n;
    }
    int Listen(int fd, int backlog)
    {
    	int n;
    	if ((n = listen(fd, backlog)) < 0)
    		perr_exit("listen error");
    	return n;
    }
    int Socket(int family, int type, int protocol)
    {
    	int n;
    	if ( (n = socket(family, type, protocol)) < 0)
    		perr_exit("socket error");
    	return n;
    }
    ssize_t Read(int fd, void *ptr, size_t nbytes) 
    {
    	ssize_t n;
    again:
    	if ( (n = read(fd, ptr, nbytes)) == -1) {  //慢速系统调用,有可能造成进程永久阻塞。
    // read 返回值: 1. >0 表示实际读到的字节数; 2. =0  数据读完,即读到文件,管道,socket末尾。 3. =-1 异常,通过errno细分, errno=EINTR 说明被信号中断,选择重启or退出;errno=EAGAIN (EWOULDBLOCK) 以非阻塞方式读并且没有数据。errno=其他值, 错误。 
    		if (errno == EINTR)
    			goto again;
    		else
    			return -1;
    	}
    	return n;
    }
    ssize_t Write(int fd, const void *ptr, size_t nbytes)
    {
    	ssize_t n;
    again:
    	if ( (n = write(fd, ptr, nbytes)) == -1) {
    		if (errno == EINTR)
    			goto again;
    		else
    			return -1;
    	}
    	return n;
    }
    int Close(int fd)
    {
    	int n;
    	if ((n = close(fd)) == -1)
    		perr_exit("close error");
    	return n;
    }
    ssize_t Readn(int fd, void *vptr, size_t n)  //需要读取n个字节,可能要分多次读
    {
    	size_t nleft;
    	ssize_t nread;
    	char *ptr;
    
    	ptr = vptr;
    	nleft = n;
    
    	while (nleft > 0) {
    		if ( (nread = read(fd, ptr, nleft)) < 0) {
    			if (errno == EINTR)
    				nread = 0;
    			else
    				return -1;
    		} else if (nread == 0)
    			break;
    		nleft -= nread;
    		ptr += nread;
    	}
    	return n - nleft;
    }
    
    ssize_t Writen(int fd, const void *vptr, size_t n)
    {
    	size_t nleft;
    	ssize_t nwritten;
    	const char *ptr;
    
    	ptr = vptr;
    	nleft = n;
    
    	while (nleft > 0) {
    		if ( (nwritten = write(fd, ptr, nleft)) <= 0) {
    			if (nwritten < 0 && errno == EINTR)
    				nwritten = 0;
    			else
    				return -1;
    		}
    		nleft -= nwritten;
    		ptr += nwritten;
    	}
    	return n;
    }
    
    static ssize_t my_read(int fd, char *ptr)
    {
    	static int read_cnt;
    	static char *read_ptr;
    	static char read_buf[100];
    
    	if (read_cnt <= 0) {
    again:
    		if ((read_cnt = read(fd, read_buf, sizeof(read_buf))) < 0) {
    			if (errno == EINTR)
    				goto again;
    			return -1;	
    		} else if (read_cnt == 0)
    			return 0;
    		read_ptr = read_buf;
    	}
    	read_cnt--;
    	*ptr = *read_ptr++;
    	return 1;
    }
    
    ssize_t Readline(int fd, void *vptr, size_t maxlen)
    {
    	ssize_t n, rc;
    	char c, *ptr;
    	ptr = vptr;
    
    	for (n = 1; n < maxlen; n++) {
    		if ( (rc = my_read(fd, &c)) == 1) {
    			*ptr++ = c;
    			if (c == '
    ')
    				break;
    		} else if (rc == 0) {
    			*ptr = 0;
    			return n - 1;
    		} else
    			return -1;
    	}
    	*ptr = 0;
    	return n;
    }
    
    

    多进程并发服务器:

    #include <stdio.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <arpa/inet.h>
    #include "wrap.h"
    #include <string.h>
    #include <ctype.h>
    #include <sys/wait.h>
    
    #define SERVER_PORT 8888
    
    void wait_child(int signo){
        while(waitpid(0,NULL,WNOHANG)>0);
        return;
    }
    
    int main()
    {
        int lfd,cfd;
        lfd=Socket(AF_INET,SOCK_STREAM,0);
    
        struct sockaddr_in serv_addr, client_addr;
    
        bzero(&serv_addr,sizeof(serv_addr));
        serv_addr.sin_family=AF_INET;
        serv_addr.sin_port=htons(SERVER_PORT);
        serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);
        //inet_pton(AF_INET,"127.0.0.1", &serv_addr.sin_addr.s_addr);
    
        Bind(lfd,(struct sockaddr*)&serv_addr, sizeof(serv_addr));
    
        Listen(lfd,128);
        pid_t pid;
        int n,i;
        char buf[BUFSIZ];
        char ip_buf[BUFSIZ];
    
        while(1){
            socklen_t client_addr_len=sizeof(client_addr);
            cfd= Accept(lfd,(struct sockaddr*)&client_addr, &client_addr_len);
            
            printf("client ip: %s-----client port: %d
    ",
                   inet_ntop(AF_INET, &client_addr.sin_addr.s_addr, ip_buf, sizeof(ip_buf)),
                     ntohs(client_addr.sin_port));
            
            pid=fork();
            if(pid<0){
                perror("fork error");
                exit(1);
            }
            if(pid==0){
                close(lfd);
                break;
            }
            close(cfd);
            signal(SIGCHLD,wait_child);
        }
        if(pid==0){
            while(1){
                n=Read(cfd,buf,sizeof(buf));        
                if(n==0){
                    close(cfd);
                    return 0;
                }
                if(n==-1){
                    perror("read err");
                    exit(1);
                }
                for(i=0;i<n;i++){
                    buf[i]=toupper(buf[i]);
                }
                Write(cfd,buf,n);
            }
    
        }
        return 0;
    }
    

    多线程版:

    #include <stdio.h>
    #include <string.h>
    #include <arpa/inet.h>
    #include <pthread.h>
    #include <ctype.h>
    #include <unistd.h>
    #include <fcntl.h>
    
    #include "wrap.h"
    
    #define MAXLINE 8192
    #define SERV_PORT 8000
    
    struct s_info {                     //定义一个结构体, 将地址结构跟cfd捆绑
        struct sockaddr_in cliaddr;
        int connfd;
    };
    
    void *do_work(void *arg)
    {
        int n,i;
        struct s_info *ts = (struct s_info*)arg;
        char buf[MAXLINE];
        char str[INET_ADDRSTRLEN];      //#define INET_ADDRSTRLEN 16  可用"[+d"查看
    
        while (1) {
            n = Read(ts->connfd, buf, MAXLINE);                     //读客户端
            if (n == 0) {
                printf("the client %d closed...
    ", ts->connfd);
                break;                                              //跳出循环,关闭cfd
            }
            printf("received from %s at PORT %d
    ",
                    inet_ntop(AF_INET, &(*ts).cliaddr.sin_addr.s_addr, str, sizeof(str)),
                    ntohs((*ts).cliaddr.sin_port));                 //打印客户端信息(IP/PORT)
    
            for (i = 0; i < n; i++) 
                buf[i] = toupper(buf[i]);                           //小写-->大写
    
            Write(STDOUT_FILENO, buf, n);                           //写出至屏幕
            Write(ts->connfd, buf, n);                              //回写给客户端
        }
        Close(ts->connfd);
    
        return (void *)0;
    }
    
    int main(void)
    {
        struct sockaddr_in servaddr, cliaddr;
        socklen_t cliaddr_len;
        int listenfd, connfd;
        pthread_t tid;
        struct s_info ts[256];      //根据最大线程数创建结构体数组.
        int i = 0;
    
        listenfd = Socket(AF_INET, SOCK_STREAM, 0);                     //创建一个socket, 得到lfd
    
        bzero(&servaddr, sizeof(servaddr));                             //地址结构清零
        servaddr.sin_family = AF_INET;
        servaddr.sin_addr.s_addr = htonl(INADDR_ANY);                   //指定本地任意IP
        servaddr.sin_port = htons(SERV_PORT);                           //指定端口号 8000
    
        Bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)); //绑定
    
        Listen(listenfd, 128);      //设置同一时刻链接服务器上限数
    
        printf("Accepting client connect ...
    ");
    
        while (1) {
            cliaddr_len = sizeof(cliaddr);
            connfd = Accept(listenfd, (struct sockaddr *)&cliaddr, &cliaddr_len);   //阻塞监听客户端链接请求
            ts[i].cliaddr = cliaddr;
            ts[i].connfd = connfd;
    
            /* 达到线程最大数时,pthread_create出错处理, 增加服务器稳定性 */
            pthread_create(&tid, NULL, do_work, (void*)&ts[i]);
            pthread_detach(tid);                                                    //子线程分离,防止僵线程产生.
            i++;
        }
    
        return 0;
    }
    
    
    





  • 相关阅读:
    tf.get_variable
    tf.Variable
    tf.placeholder
    conda命令详解
    linux查看程序运行时占用的内存
    ubuntu安装openssh-server
    sed命令
    二分查找
    vue简单使用
    斐波那契数列求解
  • 原文地址:https://www.cnblogs.com/FEIIEF/p/13050299.html
Copyright © 2020-2023  润新知