多线程聊天室服务器初步搭建

1、服务器:server.h

 1 #pragma once
 2 
 3 #include <stdio.h>
 4 #include <sys/socket.h>
 5 #include <sys/types.h>
 6 #include <arpa/inet.h>
 7 #include <netinet/in.h>
 8 #include <unistd.h>
 9 #include <stdlib.h>
10 #include <pthread.h>
11 #include <string>
12 #include <cstring>
13 #include <signal.h>
14 #include "MyDataBase.h"
15 
16 using std::string;
17 
18 #define LISTENQ 5
19 #define MAX_NUM 2
20 
21 void SetUp(u_short port, int family, int type, string db, string tb);    //服务器配置
22 void Socket(int protocal);  
23 void Bind();
24 void Listen(int backlog);
25 int Accept(sockaddr_in &clientaddr);
26 void error_msg(string msg);
27 void Run();    //运行监听
28 void *Fun(void *arg);    //线程服务函数
29 void sig_act(int signo);
30 void Start(int protocal = 0, int backlog = 1024);   //运行服务器
31 void first(int idx);    //客户端登录或注册

 

2、账号密码管理:MyDataBase.h

 1 #pragma once
 2 
 3 #include <mysql/mysql.h>
 4 #include <string>
 5 #include <vector>
 6 #include <iostream>
 7 
 8 using std::string;
 9 using std::vector;
10 
11 class MyDataBase
12 {
13 private:
14     MYSQL *sql;
15     MYSQL_RES *res;
16     MYSQL_ROW row;
17     bool connect_flag;
18     void showres();
19 public:
20     MyDataBase();
21     MyDataBase(MYSQL *mysql);
22     ~MyDataBase();
23     void connect(const string host, const string user, const string password, 
24                     const string database = "mysql", unsigned int port = 0, 
25                     const char *unix_socket = nullptr, unsigned long client_flag = 0);
26     void disconnect();
27     void showdb();
28     void createdb(const string &database);
29     void usedb(const string &database);
30     void deletedb(const string &database);
31     void showtb();
32     void createtb(const string &table, const string &elements);
33     vector<vector<string>> selectitem(const string &table, const string &value);
34     vector<vector<string>> selectitem(const string &table, const string &value, const string &limits);
35     void insertitem(const string &table, const string &value);
36     void insertitem(const string &table, const string &value, const string &col);
37     void deleteitem(const string &table, const string &value);
38     void updateitem(const string &table, const string &value, const string &limits);
39     void query(const string &command);
40 };

 

3、demo:main.cpp

1 #include "Server.h"
2 
3 int main(int argc, char const *argv[])
4 {        
5     SetUp(9999, AF_INET, SOCK_STREAM, "mydb", "test2");        
6     Start();
7     Run();
8     return 0;
9 }

 

运行结果:

 

服务器:建立连接、连接数据库、接收并转发消息

客户端:连接服务器、发送并接收消息

 

完整源码:https://github.com/Zzzy14/Function/tree/master/MyChatServer

 

总结:

1、实现了一个聊天室基本的功能,不过比较简陋,可以完善:登录过程异常处理,提供密码修改服务,设置id账号及查重等

2、服务器性能有待测试

 

posted @ 2018-07-31 20:56  Zzz...y  阅读(332)  评论(0编辑  收藏  举报