本文编的是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
|