c++局域网聊天工具

· · 个人记录

:::info[服务端]

// 编译:g++ server.cpp -o server.exe -std=c++11 -lws2_32
// 兼容:Windows 7/8/10/11 | 编码:GBK
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0500
#endif
#include <iostream>
#include <winsock2.h>
#include <vector>
#include <thread>
#include <mutex>
#include <string>
#include <windows.h>

using namespace std;

void color(int a) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), a); }
void gotoxy(int x, int y) { COORD pos = {(short)x, (short)y}; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos); }
void HideCursor() { CONSOLE_CURSOR_INFO cur = {1,0}; SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cur); }
void noedit() {
    HANDLE h = GetStdHandle(STD_INPUT_HANDLE); DWORD m; GetConsoleMode(h,&m);
    m &= ~ENABLE_QUICK_EDIT_MODE & ~ENABLE_INSERT_MODE & ~ENABLE_MOUSE_INPUT; SetConsoleMode(h,m);
}

struct Client { SOCKET sock; string name; };
vector<Client> clients; mutex mtx;
const int PORT = 8888, BUF = 2048;
string announce = ""; bool run = true;

const int COL_TITLE = 11, COL_LOG = 10, COL_WARN = 14, COL_ERR = 12, COL_NORMAL = 7;

void sendAll(const string& msg, SOCKET skip = INVALID_SOCKET) {
    lock_guard<mutex> lock(mtx);
    for (auto it=clients.begin(); it!=clients.end();) {
        if (it->sock == skip) { ++it; continue; }
        if (send(it->sock, msg.c_str(), msg.size(), 0) == SOCKET_ERROR)
        { closesocket(it->sock); it = clients.erase(it); }
        else ++it;
    }
}

void clientWork(SOCKET sock) {
    char buf[BUF] = {0};
    int ret = recv(sock, buf, BUF, 0);
    if (ret <= 0) { closesocket(sock); return; }
    string name = buf;

    { lock_guard<mutex> lock(mtx); clients.push_back({sock, name}); }
    color(COL_LOG); cout << "[上线] " << name << " 加入聊天室" << endl; color(COL_NORMAL);
    sendAll("[SYS]" + name + " 加入了聊天室");
    if (!announce.empty()) send(sock, ("[ANN]" + announce).c_str(), announce.size()+5, 0);

    while (run) {
        memset(buf,0,BUF); ret = recv(sock, buf, BUF, 0);
        if (ret <= 0) break;
        sendAll(string(buf, ret), sock);
    }

    { lock_guard<mutex> lock(mtx);
        for (auto it=clients.begin();it!=clients.end();++it) if (it->sock==sock) { clients.erase(it); break; }
    }
    closesocket(sock);
    color(COL_WARN); cout << "[离线] " << name << " 离开聊天室" << endl; color(COL_NORMAL);
    sendAll("[SYS]" + name + " 离开了聊天室");
}

void adminThread() {
    string cmd;
    while (run) {
        gotoxy(0,20); color(COL_TITLE); cout << "[管理员] > "; color(COL_NORMAL);
        getline(cin, cmd); if (cmd.empty()) continue;
        system("cls"); system("title 机房聊天服务端");

        if (cmd.find("/announce ") == 0) {
            announce = cmd.substr(10);
            sendAll("[ANN]" + announce);
            color(COL_LOG); cout << "[成功] 公告已发布" << endl;
        }
        else if (cmd == "/clearannounce") { announce = ""; sendAll("[ANN_CLR]"); color(COL_LOG); cout << "[成功] 公告已清空" << endl; }
        else if (cmd.find("/broadcast ") == 0) { sendAll("[SYS]管理员通知:" + cmd.substr(11)); color(COL_LOG); cout << "[成功] 全局消息已发送" << endl; }
        else if (cmd == "/list") {
            color(COL_TITLE); cout << "在线用户列表:" << endl; color(COL_NORMAL);
            for (auto& c : clients) cout << "- " << c.name << endl;
        }
        else if (cmd == "/help") {
            cout << "/announce 内容  发布公告" << endl;
            cout << "/clearannounce 清空公告" << endl;
            cout << "/broadcast 内容 全局通知" << endl;
            cout << "/list 查看在线用户" << endl;
            cout << "/exit 关闭服务端" << endl;
        }
        else if (cmd == "/exit") { sendAll("[SYS]服务端已关闭"); exit(0); }
        else { color(COL_ERR); cout << "[错误] 未知命令" << endl; color(COL_NORMAL); }
    }
}

void showServerUI() {
    system("cls");
    color(COL_TITLE);
    cout << "=====================================" << endl;
    cout << "       机房聊天服务端 运行中" << endl;
    cout << "=====================================" << endl;
    cout << "端口号:" << PORT << endl;
    cout << "=====================================" << endl << endl;
    color(COL_NORMAL);
}

int main() {
    system("title 机房聊天服务端");
    system("mode con cols=45 lines=25");
    noedit(); HideCursor(); showServerUI();

    WSADATA wsa; WSAStartup(MAKEWORD(2,2), &wsa);
    SOCKET listenSock = socket(AF_INET, SOCK_STREAM, 0);
    sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(PORT);
    addr.sin_addr.s_addr = INADDR_ANY;
    bind(listenSock, (sockaddr*)&addr, sizeof(addr));
    listen(listenSock, 10);

    thread(adminThread).detach();
    color(COL_LOG); cout << "[就绪] 等待客户端连接..." << endl; color(COL_NORMAL);

    while (run) {
        SOCKET sock = accept(listenSock, NULL, NULL);
        if (sock == INVALID_SOCKET) continue;
        thread(clientWork, sock).detach();
    }

    closesocket(listenSock); WSACleanup();
    return 0;
}

::: :::info[用户端]

// 编译:g++ client.cpp -o client.exe -std=c++11 -lws2_32
// 兼容:Windows 7/8/10/11 | 编码:GBK
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0500
#endif
#include <iostream>
#include <winsock2.h>
#include <thread>
#include <mutex>
#include <string>
#include <conio.h>
#include <windows.h>
#include <regex>

using namespace std;
#define kd(x) (GetAsyncKeyState(x)&0x8000)

HANDLE hCon; mutex mtx;
const int COL = 90, LINE = 30, INPUT_LINE = 27, STATUS_LINE = 28, MSG_START = 3, MSG_END = 26;
int msgLine = MSG_START;
SOCKET sock; string userName;
string ann = ""; int myColor = 10;
bool run = true;

const int COL_TITLE = 11, COL_ANN = 12, COL_SELF = 10, COL_OTHER = 9, COL_SYS = 14, COL_NORMAL = 7;

void color(int c) { SetConsoleTextAttribute(hCon, c); }
void gotoxy(int x, int y) { COORD p = {(short)x, (short)y}; SetConsoleCursorPosition(hCon, p); }
void HideCursor() { CONSOLE_CURSOR_INFO c = {1,0}; SetConsoleCursorInfo(hCon, &c); }
void ShowCursor() { CONSOLE_CURSOR_INFO c = {1,1}; SetConsoleCursorInfo(hCon, &c); }
void noedit() {
    HANDLE h = GetStdHandle(STD_INPUT_HANDLE); DWORD m;
    GetConsoleMode(h,&m); m &= ~ENABLE_QUICK_EDIT_MODE; SetConsoleMode(h,m);
}

void setFont(int size) {
    if (size<8||size>32) return;
    CONSOLE_FONT_INFOEX f = {sizeof(f)};
    f.dwFontSize.Y = size; wcscpy_s(f.FaceName, L"SimSun");
    SetCurrentConsoleFontEx(hCon, 0, &f);
}

void fontSize() {
    static int s = 16;
    if (kd(VK_CONTROL) && kd(VK_ADD)) { s+=2; setFont(s); Sleep(200); }
    if (kd(VK_CONTROL) && kd(VK_SUBTRACT)) { s-=2; setFont(s); Sleep(200); }
    if (kd(VK_CONTROL) && kd('0')) { s=16; setFont(s); Sleep(200); }
}

void drawBorder() {
    system("cls");
    color(COL_TITLE);
    cout << "=======================================================" << endl;
    cout << "                   机房联机聊天室" << endl;
    cout << "=======================================================" << endl;
    gotoxy(0,MSG_END+1); cout << "=======================================================" << endl;
    gotoxy(0,STATUS_LINE); cout << "=======================================================" << endl;
    color(COL_NORMAL);
}

void showAnn() {
    lock_guard<mutex> lock(mtx);
    gotoxy(8,2); color(COL_ANN); cout << string(75,' '); gotoxy(8,2);
    if (!ann.empty()) cout << ann;
    color(COL_NORMAL);
    gotoxy(10, INPUT_LINE);
}

void print(const string& txt, int c) {
    lock_guard<mutex> lock(mtx);
    if (msgLine > MSG_END) { drawBorder(); msgLine = MSG_START; }
    gotoxy(2, msgLine); color(c); cout << string(85,' '); gotoxy(2, msgLine);
    cout << txt; msgLine++; color(COL_NORMAL);
    gotoxy(10, INPUT_LINE);
}

bool cmd(const string& c) {
    if (c.find("/color ") == 0) { myColor = atoi(c.substr(7).c_str()); print("已设置发送颜色", COL_SELF); return 1; }
    if (c == "/colorlist") { print("颜色表:0-15 分别为黑蓝绿青红紫黄白 高亮色", COL_SELF); return 1; }
    if (c == "/clear") { drawBorder(); msgLine = MSG_START; return 1; }
    if (c == "/help") { print("命令:/color 数字 /colorlist /clear /help", COL_TITLE); return 1; }
    return 0;
}

void recvThread() {
    char buf[2048] = {0};
    while (run) {
        memset(buf,0,2048);
        int r = recv(sock, buf, 2048, 0);
        if (r<=0) { print("与服务端断开连接", COL_SYS); run=0; break; }
        string m = buf;

        if (m.find("[ANN]") == 0) { ann = m.substr(5); showAnn(); continue; }
        if (m == "[ANN_CLR]") { ann = ""; showAnn(); continue; }
        if (m.find("[SYS]") == 0) { print(m.substr(5), COL_SYS); continue; }

        regex re(R"(\[COL:(\d+)\](.*))"); smatch ma;
        if (regex_search(m,ma,re)) print(ma[2], atoi(ma[1].str().c_str()));
        else print(m, COL_OTHER);
    }
}

int main() {
    hCon = GetStdHandle(STD_OUTPUT_HANDLE);
    system("title 机房聊天客户端");
    system("mode con cols=90 lines=30");
    noedit(); setFont(16); drawBorder();

    string ip; int p;
    gotoxy(2,5); cout << "服务端IP:"; cin >> ip;
    gotoxy(2,6); cout << "端口号(8888):"; cin >> p;
    gotoxy(2,7); cout << "你的昵称:"; cin >> userName;
    cin.ignore(); drawBorder();

    WSADATA wsa;
    WSAStartup(MAKEWORD(2,2), &wsa);
    sock = socket(AF_INET, SOCK_STREAM, 0);

    sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(p);
    addr.sin_addr.s_addr = inet_addr(ip.c_str());

    if (connect(sock, (sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
        print("连接服务端失败", COL_SYS); system("pause"); return 0;
    }
    send(sock, userName.c_str(), userName.size(), 0);
    thread(recvThread).detach();

    print("欢迎你," + userName, COL_SELF);
    string input;
    while (run) {
        fontSize(); ShowCursor(); gotoxy(10, INPUT_LINE);
        if (_kbhit()) {
            char c = _getch();
            if (c == 27) { print("已退出聊天室", COL_SYS); run=0; break; }
            if (c == '\r' && !input.empty()) {
                if (!cmd(input)) {
                    string msg = "[COL:" + to_string(myColor) + "][" + userName + "] " + input;
                    send(sock, msg.c_str(), msg.size(), 0);
                    print("[" + userName + "] " + input, myColor);
                }
                input.clear(); gotoxy(10,INPUT_LINE); cout << string(75,' '); gotoxy(10,INPUT_LINE);
            } else if (c == '\b' && !input.empty()) { input.pop_back(); cout << "\b \b";
            } else if (c>=32 && c<=126 && input.size()<70) { input += c; cout << c; }
        }
        Sleep(10);
    }

    closesocket(sock); WSACleanup();
    return 0;
}

:::