使用libuv建立tcp server
更新記錄
item | note |
---|---|
20160517 | 第一版 |
目錄
libuv tcp server
範例說明
- source code
- uv_tcp_t is a subclass of uv_stream_t.
- Represents a TCP stream or TCP server.
- uv_ip4_addr(ip, port, addr) : 由ip/port取得ip4 addr
- uv_tcp_bind
- Call uv_listen on the handle to have a callback invoked whenever a new connection is established by a client.
範例內容
1 | int main() { |
on_new_connection
- Use uv_accept to accept the connection.
1 | void on_new_connection(uv_stream_t *server, int status) { |
echo_read
- 分析取得資料
- 及回應client(response)
1 | void echo_read(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) { |
tcp client
1 | void on_connect(uv_connect_t *req, int status) |
範例測試
tcp server
1 | [ubuntu](master-79103b8)15h41m root@e8b0cd737680:[t07_tcp-echo-server]$ ./t07-main-ubuntu |
tcp client
1 | [ubuntu](master-79103b8)15h41m root@e8b0cd737680:[t07_tcp-client]$ ./t07-main-ubuntu |
其它
getaddrinfo取得相關訊息
1 | struct addrinfo { |
- ai_family
- This field specifies the desired address family for the returned addresses.
- ai_family参数指定调用者期待返回的套接口地址结构的类型。它的值包括三种:AF_INET,AF_INET6和AF_UNSPEC。
- 如果指定AF_INET,那么函数九不能返回任何IPV6相关的地址信息
- 指定了AF_INET6,则就不能返回任何IPV4地址信息
- AF_UNSPEC
- 某个主机既有AAPC记录(IPV6)地址,同时又有BBPC记录(IPV4)地址,那么AAPC记录将作为sockaddr_in6结构返回,而BBPC记录则作为sockaddr_in结构返回
- AF_UNSPEC则意味着函数返回的是适用于指定主机名和服务名且适合任何协议族的地址
- The value AF_UNSPEC indicates that getaddrinfo() should return socket addresses for any address family (either IPv4 or IPv6, for example)