socket服务器编程1:server端将接收到的字符串转换为大写字母并输出

 1 //server.hpp
 2 
 3 */
 4 #ifndef _SOCKET_HPP_
 5 #define _SOCKET_HPP_
 6 
 7 #include <sys/socket.h>
 8 #include <sys/types.h>
 9 #include <arpa/inet.h>
10 #include <string.h>
11 #include <ctype.h>
12 
13 #endif
14 
15 /*===============================================================
16 *  Copyright(C) 2020 Burgess Fan aLL rights reserved.
17 *  
18 *  文件名称:server.cpp
19 *   创 建 者:Burgess
20 *   创建日期:2020年05月14日
21 ================================================================
22 */
23 
24 #include <stdio.h>
25 #include <unistd.h>
26 #include <stdlib.h>
27 #include "socket.hpp"
28 
29 #define SERV_PORT 8000
30 #define SERV_IP "192.168.35.139"
31 
32 #define handle_err(msg) \
33     do{perror(msg);exit(EXIT_FAILURE);}while(0)
34 #define MAX_SOCK_QUEUE 128
35 #define BUFSIZE    128
36 
37 int main()
38 {   
39     int serv_fd,c_fd;
40     struct sockaddr_in serv_addr,c_addr;
41     socklen_t c_addr_len;
42     int n,i;
43     char r_buf[BUFSIZE];
44     //1.建立套接字socket()
45     serv_fd=socket(AF_INET,SOCK_STREAM,0);
46     if(serv_fd<0)
47     {
48         handle_err("socket error");
49     }
50     serv_addr.sin_family=AF_INET;
51     serv_addr.sin_port=htons(SERV_PORT);//host to network long
52     serv_addr.sin_addr.s_addr=htons(INADDR_ANY);
53     //serv_addr.sin_addr.s_addr=inet_addr(SERV_IP);
54     //2.绑定IP端口号bind()
55     int ret=bind(serv_fd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
56     if(ret<0)
57     {
58         handle_err("bind error");
59     }
60     //3.指定最大同时发起连接数
61     int listen_ret=listen(serv_fd,MAX_SOCK_QUEUE);
62     if(listen_ret<0)
63     {
64         handle_err("listen_ret");
65     }
66     c_addr_len=sizeof(c_addr);
67     //4.accept阻塞等待客户端发起连接
68     c_fd=accept(serv_fd,(struct sockaddr*)&c_addr,&c_addr_len);
69     memset(r_buf,0,sizeof(BUFSIZE));
70     //5.read()
71     while(1)
72     {
73         n=read(c_fd,r_buf,sizeof(r_buf));
74         //6.小写字母变为大写字母
75         for(i=0;i<n;++i)
76         {
77             r_buf[i]=toupper(r_buf[i]);
78         }
79     //7.write()
80         write(c_fd,r_buf,n);
81         printf("%s",r_buf);
82     }
83     close(serv_fd);
84     close(c_fd);
85 }

 

posted @ 2020-05-15 00:21  弗莱曼飞侠  阅读(344)  评论(0编辑  收藏  举报