-
Notifications
You must be signed in to change notification settings - Fork 0
/
communication.cpp
92 lines (87 loc) · 2.4 KB
/
communication.cpp
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
88
89
90
91
92
#include "communication.h"
communication::communication()
{
circle_info=true;
//create server socket
server_socket=socket(AF_INET, SOCK_STREAM, 0);
if(server_socket<0)
{
cout<<"init server_socket error,return value is"<<server_socket<<endl;
cout<<"program will exit -1"<<endl;
exit(-1);
}
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family=AF_INET;
server_addr.sin_addr.s_addr=htonl(INADDR_ANY);
server_addr.sin_port=htons(communication::PORT);
err_info=bind(server_socket,(sockaddr*)&server_addr,sizeof(server_addr));
if(err_info<0)
{
cout<<"bind addr and port error, return value is"<<err_info<<endl;
cout <<"the program will exit -2"<<endl;
exit(-2);
}
}
void communication::process_conn_server(int s)
{
ssize_t size=0;
char buffer[1024];
time_t cur_tm;
time(&cur_tm);
double current_speed=car_control.cur_speed((int)cur_tm);
while (true) {
size=read(s,buffer,1024);
time(&cur_tm);
current_speed=car_control.cur_speed(int(cur_tm));
cout<<int(buffer[0])<<endl;
if(size==0)
{
cout<<"no data"<<endl;
return;
}
//buffer 0 must be asdw or t,
int return_val=car_control.translate_kbd_to_action(int(buffer[0]));
buffer[0]=char(return_val);
gcvt(current_speed, 15, buffer);
write(s, buffer, strlen(buffer)+1);
}
}
int communication::start_listen()
{
err_info=listen(server_socket, communication::BACKLOG);
if(err_info<0)
{
cout<<"listen addr and port error, return value is"<<err_info<<endl;
cout <<"the program will exit -3"<<endl;
exit(-3);
}
int fail_time(0);
while (circle_info) {
cout<<"listening...."<<endl;
socklen_t addrlen = sizeof(sockaddr);
client_socket=accept(server_socket, (sockaddr*)&client_addr, &addrlen);
if(client_socket<0)
{
cout<<"warning: accept error,continue"<<endl;
++fail_time;
if(fail_time>3){
close(client_socket);
}
continue;
}
pid=fork();
if(pid==0)
{
close(server_socket);
process_conn_server(client_socket);
}
else
{
close(client_socket);
}
}
return 0;
}
communication::~communication()
{
}