1
#include
<
vxworks.h
>
2
#include
<
sockLib.h
>
3
#include
<
inetLib.h
>
4
#include
<
MyServer.h
>
5
6
#define
DEFAULT_SERVER_PORT 6699
7
int
server;
8
SEM_ID Server_SM;
9
/*
10
* Start the function Server() as a task in AppInit() like this:
11
* int ret = 0;
12
* ret = taskSpawn("tServer", 165, 0x0002, 1024,(FUNCPTR) Server,
13
* 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
14
*/
15
void
Server()
16
{
17
int
rc
=
0
,sd
=
0
;
18
int
addr_len
=
0
;
19
int
server_sock
=
0
;
20
struct
sockaddr_in server_addr,client_addr;
21
22
memset(
&
server_addr,
0
,
sizeof
(
struct
sockaddr_in));
23
memset(
&
client_addr,
0
,
sizeof
(
struct
sockaddr_in));
24
server_sock
=
socket(AF_INET,SOCK_STREAM,
0
);
25
if
(server_sock
<
0
)
26
{
27
printf(
"
Failed to create Socket.\n
"
);
28
return
;
29
}
30
server_addr.sin_family
=
AF_INET;
31
server_addr.sin_addr.s_addr
=
htonl(INADDR_ANY);
32
server_addr.sin_port
=
htons(DEFAULT_SERVER_PORT);
33
rc
=
bind(server_sock,(
struct
sockaddr
*
)
&
server_addr,
sizeof
(
struct
sockaddr_in));
34
if
(rc
==
-
1
)
35
{
36
close(server_sock);
37
printf(
"
Failed to bind socket\n
"
);
38
return
;
39
}
40
rc
=
listen(server_sock,
2
);
41
if
(rc
==
-
1
)
42
{
43
printf(
"
socket listen error\n
"
);
44
return
;
45
}
46
printf(
"
TCP server is ready for receive connection request\n
"
);
47
while
(
1
)
48
{
49
addr_len
=
sizeof
(
struct
sockaddr_in);
50
sd
=
accept(server_sock,(
struct
sockaddr
*
)
&
client_addr,
&
addr_len);
51
if
(sd
<=
0
)
52
{
53
printf(
"
socket accept error\n
"
);
54
return
;
55
}
56
else
57
{
58
printf(
"
Socket connect success\n
"
);
59
server
=
sd;
60
server_proc(sd);
61
}
62
}
63
}
64
65
void
server_proc(
int
sock)
66
{
67
int
rc
=
0
;
68
char
buffer[
32
];
69
fd_set socket;
70
struct
timeval wait;
71
72
wait.tv_sec
=
0
;
73
wait.tv_usec
=
500000
;
74
75
while
(server
>
0
)
76
{
77
FD_ZERO(
&
socket);
78
FD_SET(sock,
&
socket);
79
80
rc
=
select(FD_SETSIZE,
&
socket,(fd_set
*
)
0
,(fd_set
*
)
0
,
&
wait);
81
if
(rc
==
0
)
82
continue
;
83
if
(FD_ISSET(sock,
&
socket))
84
{
85
semTake(Server_SM, WAIT_FOREVER);
86
memset(buffer,
0
,
sizeof
(buffer));
87
rc
=
recv(sock,buffer,
sizeof
(buffer),
0
);
88
if
(rc
>
0
)
89
{
90
/*
you can add your application specific code here
*/
91
printf(
"
RecvMsg:%s\n
"
,buffer);
92
semGive(Server_SM);
93
}
94
else
95
{
96
printf(
"
Socket closed\n
"
);
97
close(sock);
98
server
=
0
;
99
semGive(Server_SM);
100
break
;
101
}
102
}
103
taskDelay(
10
);
104
}
105
106
}
107
108
/*
end of the file
*/