Linux Socket 编程实例(一个Echo程序)

本文编的是echo服务器示例程序,当收到客户端的数据,服务器把数据不经加工地发送给客户。采用TCP连接,采用端口8080进行设计,在整个过程中主要涉及socket的通信。

1. [代码]echo_server.c     

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <netdb.h>
#include <sys/socket.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
 
#define EHCO_PORT    8080
#define MAX_CLIENT_NUM        10
 
int main()
{
     int socketfd;
     socketfd = socket(AF_INET, SOCK_STREAM, 0);
        
     if (socketfd == -1)
     {
         printf ( "errno=%d " , errno );
         exit (1);
     }
     else
     {
         printf ( "socket create successfully " );
     }
 
     struct sockaddr_in sa;
     bzero(&sa, sizeof (sa));
     sa.sin_family = AF_INET;
     sa.sin_port = htons(EHCO_PORT);
     sa.sin_addr.s_addr = htons(INADDR_ANY);
     bzero(&(sa.sin_zero), 8);
 
     if (bind(socketfd, ( struct sockaddr *)&sa, sizeof (sa))!= 0)
     {
         printf ( "bind failed " );
         printf ( "errno=%d " , errno );
         exit (1);
     }
     else
     {
         printf ( "bind successfully " );
     }
 
     //listen
     if (listen(socketfd ,MAX_CLIENT_NUM) != 0)
     {
         printf ( "listen error " );
         exit (1);
     }
     else
     {
         printf ( "listen successfully " );
     }
 
     int clientfd;
     struct sockaddr_in clientAdd;
     char buff[101];
     socklen_t len = sizeof (clientAdd);
     int closing =0;
     while ( closing == 0  && (clientfd = accept(socketfd, ( struct sockaddr *)&clientAdd, &len)) >0 )
     {
         int n;
         while ((n = recv(clientfd,buff, 100,0 )) > 0)
         {
             printf ( "number of receive bytes = %d " , n);
             write(STDOUT_FILENO, buff, n);
             send(clientfd, buff, n, 0);
             buff[n] = '' ;
             if ( strcmp (buff, "quit " ) == 0)
             {
                 break ;
             }
             else if ( strcmp (buff, "close " ) == 0)
             {
                 //server closing
                 closing = 1;
                 printf ( "server is closing " );
                 break ;
             }
         }
 
         close(clientfd);
     }
 
     close(socketfd);
 
     return 0;
}

2. [代码]测试方法     

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
linyongting@linyongting:~$ telnet 192.168.0.69 8080
Trying 192.168.0.69...
Connected to 192.168.0.69.
Escape character is '^]' .
hello! This is my first packet.Can you reply to me?
hello! This is my first packet.Can you reply to me?
Ohh, U did it!
Ohh, U did it!
see U next time !!!
see U next time !!!
quit
quit
Connection closed by foreign host.
linyongting@linyongting:~$ telnet 192.168.0.69 8080
Trying 192.168.0.69...
Connected to 192.168.0.69.
Escape character is '^]' .
close
close
Connection closed by foreign host.

3. [代码]服务器运行日志     

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
linyongting@linyongting:~ /program/c $ . /echoServer
socket create successfully
bind successfully
listen successfully
// 第一次通信
number of receive bytes = 53
hello! This is my first packet.Can you reply to me?
number of receive bytes = 16
Ohh, U did it!
number of receive bytes = 20
see U next time !!!
number of receive bytes = 6
quit
// 第二次通信
number of receive bytes = 7
close
server is closing

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 Linux socket 编程实例,展示了如何实现一个简单的客户端和服务器程序: 服务器端代码: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #define PORT 8888 int main() { int server_fd, client_fd, valread; struct sockaddr_in address; int opt = 1; int addrlen = sizeof(address); char buffer[1024] = {0}; const char *hello = "Hello from server"; // 创建 socket 文件描述符 if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) { perror("socket failed"); exit(EXIT_FAILURE); } // 设置 socket 选项 if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) { perror("setsockopt"); exit(EXIT_FAILURE); } address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(PORT); // 绑定 socket 到指定地址和端口号 if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) { perror("bind failed"); exit(EXIT_FAILURE); } // 监听 socket if (listen(server_fd, 3) < 0) { perror("listen"); exit(EXIT_FAILURE); } // 接受客户端连接 if ((client_fd = accept(server_fd, (struct sockaddr *)&address, (socklen_t *)&addrlen)) < 0) { perror("accept"); exit(EXIT_FAILURE); } // 从客户端接收数据 valread = read(client_fd, buffer, 1024); printf("%s\n", buffer); // 向客户端发送数据 send(client_fd, hello, strlen(hello), 0); printf("Hello message sent\n"); return 0; } ``` 客户端代码: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #define PORT 8888 int main(int argc, char const *argv[]) { int sock = 0, valread; struct sockaddr_in serv_addr; char *hello = "Hello from client"; char buffer[1024] = {0}; // 创建 socket 文件描述符 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("\n Socket creation error \n"); return -1; } memset(&serv_addr, '0', sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT); // 将 IPv4 地址从点分十进制转换为二进制格式 if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) { printf("\nInvalid address/ Address not supported \n"); return -1; } // 连接到服务器 if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { printf("\nConnection Failed \n"); return -1; } // 向服务器发送数据 send(sock, hello, strlen(hello), 0); printf("Hello message sent\n"); // 从服务器接收数据 valread = read(sock, buffer, 1024); printf("%s\n", buffer); return 0; } ``` 以上代码实现了一个简单的客户端和服务器程序,客户端向服务器发送 "Hello from client" 字符串,服务器接收到后向客户端发送 "Hello from server" 字符串。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值