#include <iostream>
#include <thread>
#include <string>
#include <vector>
#include <chrono>
#include <ctime>
#include <unistd.h>
#include <bits/stdc++.h>
using namespace std;
using json = nlohmann::json;
#define PASSWOED_LENGTH 50
#define NAME_LENGTH 50
#define BUFFER_SIZE 1024
//记录当前系统登录的用户信息
User g_current_user;
//记录当前登录用户的好友列表信息
vector<User> g_current_friends_list;
//记录当前登录用户的群组列表信息
vector<Group> g_current_group_list;
//显示当前登录成功用户的基本信息
void ShowCurrentUserData();
//接收用户收到消息的线程
void ReadTaskHandler(int client_fd);
//获取系统时间
string GetCurrentTime();
//主聊天页面程序
void MainMenu(int client_fd);
// "help" command handler
void Help(int fd = 0, string str = "");
// "chat" command handler
void Chat(int, string);
// "addfriend" command handler
void AddFriend(int, string);
// "creategroup" command handler
void CreateGroup(int, string);
// "addgroup" command handler
void AddGroup(int, string);
// "groupchat" command handler
void GroupChat(int, string);
// "loginout" command handler
void LoginOut(int, string);
//控制主菜单是否继续显示
bool g_is_menu_running = false;
// 系统支持的客户端命令列表
unordered_map<string, string> command_map = {
{"help", "显示所有支持的命令,格式help"},
{"chat", "一对一聊天,格式chat:friendid:message"},
{"addfriend", "添加好友,格式addfriend:friendid"},
{"creategroup", "创建群组,格式creategroup:groupname:groupdesc"},
{"addgroup", "加入群组,格式addgroup:groupid"},
{"groupchat", "群聊,格式groupchat:groupid:message"},
{"loginout", "注销,格式loginout"}};
// 注册系统支持的客户端命令处理
unordered_map<string, function<void(int, string)>> command_handler_map = {
{"help", Help},
{"chat", Chat},
{"addfriend", AddFriend},
{"creategroup", CreateGroup},
{"addgroup", AddGroup},
{"groupchat", GroupChat},
{"loginout", LoginOut}};
///
//main函数主要获取用户的输入,接收线程则是将用户收到的信息打印出来
//集成登录、注册功能
int main(int argc, char **argv)
{
if (argc < 3)
{
cerr << "command invaild example: ./ExeNAME IpAddress port" << endl;
exit(-1);
}
//解析IP地址和端口号
char *ip = argv[1];
uint16_t port = atoi(argv[2]);
//创建socket
int clientfd = socket(AF_INET, SOCK_STREAM, 0);
if (clientfd == -1)
{
cerr << "create socket error" << endl;
exit(-1);
}
//录入连接server服务器信息
sockaddr_in server;
memset(&server, 0, sizeof(sockaddr_in));
server.sin_family = AF_INET;
server.sin_port = htons(port);
server.sin_addr.s_addr = inet_addr(ip);
//server与clientfd连接
if (-1 == connect(clientfd, (sockaddr *)&server, sizeof(sockaddr_in)))
{
cout << "connect error" << endl;
close(clientfd);
exit(-1);
}
//主业务
for (;;)
{
//显示首页面菜单 登录,注册,退出
cout << "**********welcome**********" << endl;
cout << " 1. login" << endl;
cout << " 2. register" << endl;
cout << " 3. quit " << endl;
cout << "please input your choice:";
int choice = 0;
cin >> choice;
//处理读入 缓冲区的回车
cin.get();
switch (choice)
{
case 1:
{
int id = 0;
char pwd[PASSWOED_LENGTH] = {0};
cout << "please input id:";
cin >> id;
cin.get();
cout << "please input password:";
cin
C++聊天室客户端
于 2023-05-31 21:31:58 首次发布
本文介绍了如何使用C++编程语言开发一款聊天室客户端。内容涵盖C++的基础知识,网络编程概念,以及如何实现客户端与服务器之间的数据通信,构建简单的聊天功能。
摘要由CSDN通过智能技术生成