基于libuv库的简单UDP聊天客户端+服务端

udpserver

//udpserver.cpp
#include 
#include 
#include "uv.h"


uv_udp_t udp_server;
uv_connect_t connect_req;
uv_write_t write_req;
struct sockaddr_in addr;
uv_buf_t buf;
uv_thread_t thread_recv;
uv_thread_t thread_watch_;
uv_loop_t loop_;

#define TCP_SERVER_IP "127.0.0.1"
#define TCP_SERVER_PORT 9000

static void write_cb(uv_write_t *req, int status) {
    std::cout<<__LINE__<<" write_cb-- status="<handle, NULL);
    if (status) {
        fprintf(stderr, "Write error %s\n", uv_strerror(status));
    }
    free(req);
}

static void close_cb(uv_handle_t* handle) {
     std::cout<<__LINE__<<" -- close_cb="<base<base, nread);

        uv_udp_send_t* req = (uv_udp_send_t*)malloc(sizeof(uv_udp_send_s));;
        int ret = uv_udp_send(req, handle, &uvBuf, 1, addr, on_udp_send);
        std::cout<<__LINE__<<"  ret="<base);
}

void on_close(uv_handle_t* handle) {
    free(handle);
}

static void thread_recv_data(void* arg)
{
    std::cout<<__LINE__<<" -- thread_recv_data"<

udpclient

//udpclient.cpp
#include 
#include 
#include 
#include "uv.h"


#define TCP_SERVER_IP "127.0.0.1"
#define TCP_SERVER_PORT 9000
#define MAX_STRING_LEN 256

uv_udp_t udp_client;
uv_connect_t connect_req;
uv_udp_send_t send_req_;
uv_loop_t uv_loop_;
bool            need_loop_ = true;
//发送消息
char str_msg_[MAX_STRING_LEN]={0};
uv_buf_t uv_buf_ = {str_msg_, 0 };
uv_async_t async_handle_;


void on_close(uv_handle_t* handle) {
    std::cout<<__LINE__<<"******* 退出 ******"<base<base);
}

static void on_udp_send(uv_udp_send_t* req, int status)
{
    //std::cout << __LINE__ << "  on udp send..." << std::endl;
}

void on_client_close(uv_handle_t* handle)
{
    std::cout<<__LINE__<<"  on_client_close"<

演示:

client

~/work/udpdemo$ ./client 
hello tcp client...
thread input msg ...

请输入(q退出):
12345678
client: 12345678
46 server:12345678

请输入(q退出):
321
client: 321
46 server:321

请输入(q退出):
q
client: q
66  call uv_close
66  call uv_close
59  on_client_close
59  on_client_close
loop 正常退出 ...

server

~/work/udpdemo$ ./server 
hello, this is tcp server...
73 -- thread_recv_data
35 alloc_cb-- suggested_size=65536
47 in udp_recv_cb nread=8
54 read data = 8   data:12345678
61  ret=0  : Unknown system error 035 alloc_cb-- suggested_size=65536
47 in udp_recv_cb nread=0
42  on udp send...
35 alloc_cb-- suggested_size=65536
47 in udp_recv_cb nread=3
54 read data = 3   data:321

你可能感兴趣的:(linux,积累跬步,udp,网络协议,网络)