Skip to content

Commit 8e9e7d3

Browse files
author
zhengshuxin
committed
Add fiber udp demo.
1 parent cf0dfcc commit 8e9e7d3

File tree

5 files changed

+75
-1
lines changed

5 files changed

+75
-1
lines changed

lib_acl/samples/udp_server/main.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ static void run(const char *addr, int can_quit, int need_echo, int inter)
1212
{
1313
char buf[4096];
1414
int ret, i = 0;
15-
ACL_VSTREAM *stream = acl_vstream_bind(addr, 0, 0); /* °ó¶¨ UDP Ì×½Ó¿Ú */
15+
ACL_VSTREAM *stream = acl_vstream_bind(addr, -1, 0); /* °ó¶¨ UDP Ì×½Ó¿Ú */
1616

1717
if (stream == NULL) {
1818
printf("acl_vstream_bind %s error %s\r\n",
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
include ../Makefile_cpp.in
2+
CFLAGS += -std=c++11
3+
PROG = fiber_udpc
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
#include "stdafx.h"
2+
#include <vector>
3+
#include <thread>
4+
#include <iostream>
5+
6+
int main() {
7+
acl::fiber::stdout_open(true);
8+
9+
for (size_t i = 0; i < 5; i++) {
10+
go[] {
11+
const char* addr = "127.0.0.1:0";
12+
acl::socket_stream ss;
13+
if (!ss.bind_udp(addr, -1, acl::OPEN_FLAG_REUSEPORT)) {
14+
printf("bind %s error %s\r\n", addr, acl::last_serror());
15+
exit(1);
16+
}
17+
18+
ss.set_rw_timeout(5, true);
19+
20+
int fd = ss.sock_handle();
21+
22+
const char* dest_addr = "127.0.0.1:8888";
23+
const char* data = "hello world!";
24+
char buf[1024];
25+
26+
for (size_t j = 0; j < 5; j++) {
27+
int ret = ss.sendto(data, strlen(data), dest_addr, 0);
28+
if (ret == -1) {
29+
printf("sendto to %s error\r\n", dest_addr);
30+
break;
31+
}
32+
33+
ACL_SOCKADDR src_addr;
34+
socklen_t addrlen = sizeof(src_addr);
35+
36+
ret = ::recvfrom(fd, buf, sizeof(buf) - 1, 0,
37+
(struct sockaddr*) &src_addr, &addrlen);
38+
if (ret == -1) {
39+
printf("recvfrom error %s\r\n", acl::last_serror());
40+
break;
41+
}
42+
buf[ret] = 0;
43+
printf("recvfrom: %s\r\n", buf);
44+
}
45+
};
46+
}
47+
48+
acl::fiber::schedule();
49+
printf("All over!\r\n");
50+
return 0;
51+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
#include "stdafx.h"
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// stdafx.h : 标准系统包含文件的包含文件,
2+
// 或是常用但不常更改的项目特定的包含文件
3+
//
4+
5+
#pragma once
6+
7+
8+
// TODO: 在此处引用程序要求的附加头文件
9+
10+
#include "lib_acl.h"
11+
#include "acl_cpp/lib_acl.hpp"
12+
#include "fiber/libfiber.hpp"
13+
14+
#include "fiber/go_fiber.hpp"
15+
16+
#ifdef WIN32
17+
#define snprintf _snprintf
18+
#endif
19+

0 commit comments

Comments
 (0)