本文主要是介绍UDP畅聊,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
简介:项目是在Linux系统中CentOS6.5的环境下编写完成的,可以实现一个基本的群聊功能。客户端向服务端发送消息,服务器接收这条消息并将它发送给所有客户端,用到json库对消息序列化以及反序列化。ncurse库绘制客户端窗口。
原理图
部分代码展示如下(用到哪些模块)
服务器udp_server.h
#pragma once#include <iostream>
#include <string>
#include <map>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "data_pool.h"#define SIZE 1024class udp_server{public:udp_server(int _port);void init_server();void recv_data(std::string &out_string);void broadcast();~udp_server();private:void send_data(const std::string &in_string,const struct sockaddr_in &peer);private:int sock;int port;data_pool pool;std::map<uint32_t, struct sockaddr_in> online;
};
客户端udp_client.h
#pragma once#include <iostream>
#include <string>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>#define SIZE 1024class udp_client{public:udp_client(std::string server_ip,int server_port);void init_client();void recv_data(std::string &out_string);void send_data(const std::string &in_string);~udp_client();private:int sock;struct sockaddr_in server;
};
数据池data_pool.h
#pragma once#include <iostream>
#include <string>
#include <vector>
#include <semaphore.h>#define NUM 256class data_pool{public:data_pool(int _cap = NUM);void get_message(std::string &out_message);void put_message(const std::string &in_message);~data_pool();private:std::vector<std::string> pool;int cap;int consume_step;int product_step;sem_t space_sem;sem_t message_sem;
};
序列化和反序列化data.h
#pragma once#include <iostream>
#include <string>
#include <json/json.h>class data{public:data();void serialize(std::string &out_string);void unserialize(std::string &in_string);~data();public:std::string nick_name;std::string school;std::string message;std::string type;
};
窗口window.h
#pragma once#include <iostream>
#include <ncurses.h>#define SIZE 1024class window{public:window();void put_string_to_window(WINDOW *w, int y,\int x, std::string &message);void get_string_from_window(WINDOW *w, std::string &out_string);void draw_header();void draw_output();void draw_flist();void draw_input();WINDOW *get_header();WINDOW *get_output();WINDOW *get_flist();WINDOW *get_input();~window();private:WINDOW *header;WINDOW *output;WINDOW *flist;WINDOW *input;
};
具体结果
这篇关于UDP畅聊的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!