Apollo 10.0
自动驾驶开放平台
udp_echo_server.cc
浏览该文件的文档.
1/******************************************************************************
2 * Copyright 2018 The Apollo Authors. All Rights Reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *****************************************************************************/
16
17#include <arpa/inet.h>
18#include <netinet/in.h>
19#include <sys/socket.h>
20#include <cstdlib>
21#include <iostream>
22#include <string>
23#include <vector>
24
25#include "cyber/cyber.h"
26#include "cyber/init.h"
27#include "cyber/io/session.h"
29#include "cyber/task/task.h"
30#include "cyber/time/time.h"
31
34
35void Echo(const std::shared_ptr<Session>& session) {
36 struct sockaddr_in client_addr;
37 std::vector<char> recv_buffer(2049);
38 int nbytes = 0;
39 socklen_t sock_len = static_cast<socklen_t>(sizeof(client_addr));
40
41 while (true) {
42 nbytes = static_cast<int>(
43 session->RecvFrom(recv_buffer.data(), recv_buffer.size(), 0,
44 (struct sockaddr*)&client_addr, &sock_len));
45 if (nbytes < 0) {
46 std::cout << "recv from client failed." << std::endl;
47 continue;
48 }
49 session->SendTo(recv_buffer.data(), nbytes, 0,
50 (const struct sockaddr*)&client_addr, sock_len);
51 }
52}
53
54int main(int argc, char* argv[]) {
55 if (argc != 2) {
56 std::cout << "Usage: " << argv[0] << " <server port>" << std::endl;
57 return -1;
58 }
59
60 apollo::cyber::Init(argv[0]);
61
62 uint16_t server_port = static_cast<uint16_t>(atoi(argv[1]));
64 [&server_port]() {
65 struct sockaddr_in server_addr;
66 server_addr.sin_family = AF_INET;
67 server_addr.sin_addr.s_addr = htons(INADDR_ANY);
68 server_addr.sin_port = htons(server_port);
69
70 auto session = std::make_shared<Session>();
71 session->Socket(AF_INET, SOCK_DGRAM, 0);
72 if (session->Bind((struct sockaddr*)&server_addr, sizeof(server_addr)) <
73 0) {
74 std::cout << "bind to port[" << server_port << "] failed."
75 << std::endl;
76 return;
77 }
78 Echo(session);
79 session->Close();
80 },
81 "echo_server");
82
84 return 0;
85}
Cyber has builtin time type Time.
Definition time.h:31
bool CreateTask(const RoutineFactory &factory, const std::string &name)
Definition scheduler.cc:37
void WaitForShutdown()
Definition state.h:50
bool Init(const char *binary_name, const std::string &dag_info)
Definition init.cc:98
int main(int argc, char *argv[])
void Echo(const std::shared_ptr< Session > &session)