跳到正文

个人记录

局域网聊天

wanganze约 42 分钟
原文
文章信息与版本

文章信息

发布
2026年8月2日
收录
2026年10月11日
更新
2026年11月11日
篇幅
约 42 分钟

版本

  1. v1当前
client
C++
/*
-std=c++14
-static-libgcc -lWs2_32
*/
#include <bits/stdc++.h>
#include <thread>
#include <conio.h>
#include <winsock2.h>
#include <windows.h>
#include <ws2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")
using namespace std;

string serverIP;
int serverPort;
wstring username;

HANDLE hConsole;
mutex mtx;

wstring inputBuffer;          // 完整输入内容
size_t cursorPos = 0;         // 字符索引(按 wchar_t)
size_t displayOffset = 0;     // 当前屏幕显示从哪个索引开始

// ---------- 代理对工具 ----------
inline bool isHighSurrogate(wchar_t c) { return (c >= 0xD800 && c <= 0xDBFF); }
inline bool isLowSurrogate(wchar_t c)  { return (c >= 0xDC00 && c <= 0xDFFF); }

int getCodepointAt(const wstring& str, size_t index, size_t& nextIndex) {
    if (index >= str.size()) { nextIndex = index; return -1; }
    wchar_t c = str[index];
    if (isHighSurrogate(c) && index + 1 < str.size() && isLowSurrogate(str[index + 1])) {
        int high = c - 0xD800;
        int low = str[index + 1] - 0xDC00;
        nextIndex = index + 2;
        return (high << 10) + low + 0x10000;
    } else {
        nextIndex = index + 1;
        return (int)c;
    }
}

// 计算字符串从 start 到 start+n 的显示宽度
int calcDisplayWidth(const wstring& str, size_t start, size_t n) {
    int width = 0;
    size_t i = start;
    size_t end = min(start + n, str.size());
    while (i < end) {
        size_t next;
        int cp = getCodepointAt(str, i, next);
        if (cp == -1) break;
        width += (cp <= 0x7F) ? 1 : 2;
        i = next;
    }
    return width;
}

// 删除一个字符(可能为代理对)
size_t eraseCharAt(wstring& str, size_t pos) {
    if (pos >= str.size()) return pos;
    if (isLowSurrogate(str[pos]) && pos > 0 && isHighSurrogate(str[pos - 1])) {
        str.erase(pos - 1, 2);
        return pos - 1;
    } else if (isHighSurrogate(str[pos]) && pos + 1 < str.size() && isLowSurrogate(str[pos + 1])) {
        str.erase(pos, 2);
        return pos;
    } else {
        str.erase(pos, 1);
        return pos;
    }
}

// 删除光标前一个字符
size_t eraseBeforeCursor(wstring& str, size_t pos) {
    if (pos == 0) return pos;
    size_t prev = pos - 1;
    if (isLowSurrogate(str[prev]) && prev > 0 && isHighSurrogate(str[prev - 1])) {
        str.erase(prev - 1, 2);
        return prev - 1;
    } else {
        str.erase(prev, 1);
        return prev;
    }
}

// ---------- 编码转换 ----------
string wstring_to_utf8(const wstring& wstr) {
    if (wstr.empty()) return string();
    int size = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), (int)wstr.size(), NULL, 0, NULL, NULL);
    string result(size, 0);
    WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), (int)wstr.size(), &result[0], size, NULL, NULL);
    return result;
}

wstring utf8_to_wstring(const string& str) {
    if (str.empty()) return wstring();
    int size = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), (int)str.size(), NULL, 0);
    wstring result(size, 0);
    MultiByteToWideChar(CP_UTF8, 0, str.c_str(), (int)str.size(), &result[0], size);
    return result;
}

// ---------- 网络收发(长度头)----------
bool sendMessage(SOCKET sock, const string& msg) {
    uint32_t len = (uint32_t)msg.size();
    uint32_t netLen = htonl(len);
    if (send(sock, (char*)&netLen, sizeof(netLen), 0) != sizeof(netLen)) return false;
    if (len > 0 && send(sock, msg.c_str(), len, 0) != (int)len) return false;
    return true;
}

bool recvMessage(SOCKET sock, string& outMsg) {
    uint32_t netLen;
    int ret = recv(sock, (char*)&netLen, sizeof(netLen), 0);
    if (ret != sizeof(netLen)) return false;
    uint32_t len = ntohl(netLen);
    if (len == 0) { outMsg.clear(); return true; }
    if (len > 10 * 1024 * 1024) return false;
    outMsg.resize(len);
    size_t received = 0;
    while (received < len) {
        int r = recv(sock, &outMsg[0] + received, len - received, 0);
        if (r <= 0) return false;
        received += r;
    }
    return true;
}

// ---------- 刷新输入行(支持水平滚动)----------
void refreshInputLine_locked() {
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    GetConsoleScreenBufferInfo(hConsole, &csbi);
    int width = csbi.dwSize.X;
    int height = csbi.dwSize.Y;

    // 清空最后一行
    COORD pos = {0, (SHORT)(height - 1)};
    SetConsoleCursorPosition(hConsole, pos);
    DWORD written;
    FillConsoleOutputCharacter(hConsole, ' ', width, pos, &written);
    SetConsoleCursorPosition(hConsole, pos);

    // 确定显示范围:使光标位于合适位置
    int promptWidth = 2; // "> "
    int maxContentWidth = width - promptWidth;

    // 计算光标前的宽度(相对于光标位置)
    int cursorWidth = calcDisplayWidth(inputBuffer, 0, cursorPos);
    // 调整 displayOffset,使光标在屏幕约 70% 位置
    int targetCursorCol = (int)(maxContentWidth * 0.7);
    if (cursorWidth < targetCursorCol) {
        displayOffset = 0;
    } else {
        int totalWidth = 0;
        size_t offset = 0;
        while (offset < inputBuffer.size()) {
            size_t next;
            int cp = getCodepointAt(inputBuffer, offset, next);
            if (cp == -1) break;
            int charWidth = (cp <= 0x7F) ? 1 : 2;
            if (totalWidth + charWidth >= cursorWidth - targetCursorCol) break;
            totalWidth += charWidth;
            offset = next;
        }
        displayOffset = offset;
    }

    // 截取显示内容
    wstring displayStr;
    int displayWidth = 0;
    size_t idx = displayOffset;
    while (idx < inputBuffer.size() && displayWidth < maxContentWidth) {
        size_t next;
        int cp = getCodepointAt(inputBuffer, idx, next);
        if (cp == -1) break;
        int charWidth = (cp <= 0x7F) ? 1 : 2;
        if (displayWidth + charWidth > maxContentWidth) break;
        displayStr += inputBuffer.substr(idx, next - idx);
        displayWidth += charWidth;
        idx = next;
    }

    wstring prompt = L"> ";
    WriteConsoleW(hConsole, prompt.c_str(), (DWORD)prompt.size(), &written, NULL);
    WriteConsoleW(hConsole, displayStr.c_str(), (DWORD)displayStr.size(), &written, NULL);

    int cursorCol = promptWidth + (cursorWidth - calcDisplayWidth(inputBuffer, 0, displayOffset));
    if (cursorCol >= width) cursorCol = width - 1;
    COORD cursor = { (SHORT)cursorCol, (SHORT)(height - 1) };
    SetConsoleCursorPosition(hConsole, cursor);
}

// ---------- 打印消息(直接追加,保留历史)----------
void printMessage(const wstring& msg) {
    lock_guard<mutex> lock(mtx);

    CONSOLE_SCREEN_BUFFER_INFO csbi;
    GetConsoleScreenBufferInfo(hConsole, &csbi);
    int width = csbi.dwSize.X;
    int height = csbi.dwSize.Y;

    // 将消息拆分成若干行
    vector<wstring> lines;
    wstring currentLine;
    int currentWidth = 0;
    size_t i = 0;
    while (i < msg.size()) {
        size_t next;
        int cp = getCodepointAt(msg, i, next);
        if (cp == -1) break;
        int charWidth = (cp <= 0x7F) ? 1 : 2;
        if (currentWidth + charWidth > width) {
            lines.push_back(currentLine);
            currentLine.clear();
            currentWidth = 0;
        }
        currentLine += msg.substr(i, next - i);
        currentWidth += charWidth;
        i = next;
    }
    if (!currentLine.empty() || lines.empty()) lines.push_back(currentLine);

    // 获取当前光标位置(可能在输入行)
    COORD curPos = csbi.dwCursorPosition;
    // 如果光标在最后一行(输入行),则先上移一行
    if (curPos.Y == height - 1) {
        curPos.Y = height - 2;
        curPos.X = 0;
        SetConsoleCursorPosition(hConsole, curPos);
    }

    // 逐行输出消息
    for (size_t lineIdx = 0; lineIdx < lines.size(); ++lineIdx) {
        // 如果当前行已经是最后一行,先插入空行(将输入行下推)
        CONSOLE_SCREEN_BUFFER_INFO info;
        GetConsoleScreenBufferInfo(hConsole, &info);
        if (info.dwCursorPosition.Y == height - 1) {
            // 在输入行之前插入空行:滚动消息区域(0 到 height-2)向上,但我们需要插入新行
            // 简单的做法:输出换行符,但会改变输入行位置,所以我们采用更稳健的方法:
            // 将消息区域(0~height-2)整体上滚一行,然后光标移到刚空出的行(height-2)继续输出
            // 但我们已经放弃了滚动方式,因此这里我们采用直接输出换行,然后重新定位输入行。
            // 为了保持输入行在最后,我们可以输出换行后,将输入行重新定位到最后一行。
            // 但更简单:先输出一个换行,将光标移到下一行,然后刷新输入行到底部。
            // 但这样会使输入行下移,最终可能导致屏幕滚动,但控制台缓冲区会保留历史。
            // 我们直接输出换行符,让光标下移,然后输入行自动跟着下移,直到达到缓冲区底部。
            // 由于我们设置了较大的缓冲区高度,可以容纳许多行。
            wstring newline = L"\r\n";
            DWORD written;
            WriteConsoleW(hConsole, newline.c_str(), (DWORD)newline.size(), &written, NULL);
        }

        // 输出当前行
        DWORD written;
        WriteConsoleW(hConsole, lines[lineIdx].c_str(), (DWORD)lines[lineIdx].size(), &written, NULL);

        // 如果不是最后一行,输出换行
        if (lineIdx < lines.size() - 1) {
            wstring newline = L"\r\n";
            DWORD written;
            WriteConsoleW(hConsole, newline.c_str(), (DWORD)newline.size(), &written, NULL);
        }
    }

    // 输出换行,使下一条消息另起一行
    wstring finalNewline = L"\r\n";
    DWORD written;
    WriteConsoleW(hConsole, finalNewline.c_str(), (DWORD)finalNewline.size(), &written, NULL);

    // 现在将光标移到输入行(最后一行)并刷新输入
    // 先获取当前缓冲区尺寸
    CONSOLE_SCREEN_BUFFER_INFO info2;
    GetConsoleScreenBufferInfo(hConsole, &info2);
    // 将光标定位到缓冲区最后一行
    COORD inputPos = {0, (SHORT)(info2.dwSize.Y - 1)};
    SetConsoleCursorPosition(hConsole, inputPos);

    // 刷新输入行
    refreshInputLine_locked();
}

// ---------- 接收线程 ----------
void netRead(SOCKET sock) {
    while (true) {
        string msg_utf8;
        if (!recvMessage(sock, msg_utf8)) break;
        wstring msg = utf8_to_wstring(msg_utf8);
        printMessage(msg);
    }
}

// ---------- 用户名验证 ----------
bool isValidUsername(const string& name) {
    if (name.empty() || name.size() > 20) return false;
    for (char c : name) {
        if (!isalnum(c) && c != '_') return false;
    }
    return true;
}

// ---------- 主函数 ----------
int main() {
    hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

    // 设置控制台缓冲区高度为 1000 行(便于滚动查看历史)
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    GetConsoleScreenBufferInfo(hConsole, &csbi);
    COORD newSize = {csbi.dwSize.X, 1000};
    SetConsoleScreenBufferSize(hConsole, newSize);

    cout << "请输入服务器IP(IPv4):";
    cin >> serverIP;
    cout << "请输入服务器端口:";
    cin >> serverPort;

    WSADATA wsa_data;
    WSAStartup(MAKEWORD(2, 2), &wsa_data);

    bool connected = false;
    while (!connected) {
        cout << "\n请输入用户名(仅允许字母、数字和下划线,长度1~20):";
        string uname;
        cin >> uname;
        while (!isValidUsername(uname)) {
            cout << "用户名不合法,请重新输入:";
            cin >> uname;
        }
        username = wstring(uname.begin(), uname.end());

        SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        if (sock == INVALID_SOCKET) {
            cerr << "socket 创建失败" << endl;
            continue;
        }

        sockaddr_in server_addr;
        server_addr.sin_family = AF_INET;
        server_addr.sin_port = htons(serverPort);
        server_addr.sin_addr.s_addr = inet_addr(serverIP.c_str());

        if (connect(sock, (sockaddr*)&server_addr, sizeof(server_addr)) == SOCKET_ERROR) {
            cerr << "无法连接服务器,请检查IP和端口" << endl;
            closesocket(sock);
            continue;
        }

        string uname_utf8 = wstring_to_utf8(username);
        send(sock, uname_utf8.c_str(), uname_utf8.size() + 1, 0);

        char response;
        int recvLen = recv(sock, &response, 1, 0);
        if (recvLen <= 0 || response == 0) {
            cout << "用户名被拒绝(可能重复或不合法),请重新输入" << endl;
            closesocket(sock);
            continue;
        }

        connected = true;
        cout << "\n连接成功!开始聊天(方向键移动光标,回车发送)\n" << endl;

        thread reader(netRead, sock);
        reader.detach();

        inputBuffer.clear();
        cursorPos = 0;
        displayOffset = 0;

        while (true) {
            {
                lock_guard<mutex> lock(mtx);
                refreshInputLine_locked();
            }

            int ch = _getwch();

            if (ch == 0xE0 || ch == 0x00) {
                ch = _getwch();
                lock_guard<mutex> lock(mtx);
                switch (ch) {
                    case 0x4B: // 左
                        if (cursorPos > 0) {
                            if (isLowSurrogate(inputBuffer[cursorPos - 1]) && cursorPos >= 2 && isHighSurrogate(inputBuffer[cursorPos - 2]))
                                cursorPos -= 2;
                            else
                                --cursorPos;
                        }
                        break;
                    case 0x4D: // 右
                        if (cursorPos < inputBuffer.size()) {
                            if (isHighSurrogate(inputBuffer[cursorPos]) && cursorPos + 1 < inputBuffer.size() && isLowSurrogate(inputBuffer[cursorPos + 1]))
                                cursorPos += 2;
                            else
                                ++cursorPos;
                        }
                        break;
                    case 0x47: cursorPos = 0; break;
                    case 0x4F: cursorPos = inputBuffer.size(); break;
                    case 0x53: // Delete
                        if (cursorPos < inputBuffer.size()) {
                            cursorPos = eraseCharAt(inputBuffer, cursorPos);
                        }
                        break;
                }
                refreshInputLine_locked();
                continue;
            }

            if (ch == 13) { // 回车
                wstring msgCopy;
                {
                    lock_guard<mutex> lock(mtx);
                    if (!inputBuffer.empty()) {
                        msgCopy = inputBuffer;
                    }
                }
                if (!msgCopy.empty()) {
                    wstring fullMsg = username + L": " + msgCopy;
                    printMessage(fullMsg);
                    string msg_utf8 = wstring_to_utf8(msgCopy);
                    sendMessage(sock, msg_utf8);
                    {
                        lock_guard<mutex> lock(mtx);
                        inputBuffer.clear();
                        cursorPos = 0;
                        displayOffset = 0;
                        refreshInputLine_locked();
                    }
                } else {
                    lock_guard<mutex> lock(mtx);
                    refreshInputLine_locked();
                }
            } else if (ch == 8) { // 退格
                lock_guard<mutex> lock(mtx);
                if (cursorPos > 0) {
                    cursorPos = eraseBeforeCursor(inputBuffer, cursorPos);
                }
                refreshInputLine_locked();
            } else if (ch >= 32 && ch < 0xFFFF) {
                lock_guard<mutex> lock(mtx);
                if (isHighSurrogate((wchar_t)ch)) {
                    int low = _getwch();
                    if (isLowSurrogate((wchar_t)low)) {
                        inputBuffer.insert(cursorPos, 1, (wchar_t)ch);
                        inputBuffer.insert(cursorPos + 1, 1, (wchar_t)low);
                        cursorPos += 2;
                    } else {
                        // 忽略
                    }
                } else {
                    inputBuffer.insert(cursorPos, 1, (wchar_t)ch);
                    ++cursorPos;
                }
                // 不限制长度
                refreshInputLine_locked();
            }
        }

        closesocket(sock);
        break;
    }

    WSACleanup();
    return 0;
}
server
C++
/*
-std=c++14
-static-libgcc -lWs2_32
*/
#include <bits/stdc++.h>
#include <thread>
#include <winsock2.h>
#include <windows.h>
#include <ws2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")
using namespace std;

vector<SOCKET> socks;
map<SOCKET, string> userMap;
map<SOCKET, string> clientAddrMap;
map<SOCKET, time_t> connectTimeMap;
mutex mtx;
int port;

vector<string> getLocalIPs() {
    vector<string> ips;
    char hostname[256];
    if (gethostname(hostname, sizeof(hostname)) == 0) {
        struct hostent* he = gethostbyname(hostname);
        if (he) {
            for (int i = 0; he->h_addr_list[i] != nullptr; ++i) {
                struct in_addr addr;
                memcpy(&addr, he->h_addr_list[i], sizeof(addr));
                string ip = inet_ntoa(addr);
                if (ip != "127.0.0.1") ips.push_back(ip);
            }
        }
    }
    if (ips.empty()) ips.push_back("0.0.0.0");
    return ips;
}

bool isValidUsername(const string& name) {
    if (name.empty() || name.size() > 20) return false;
    for (char c : name) {
        if (!isalnum(c) && c != '_') return false;
    }
    return true;
}

// 接收完整消息(长度头+内容)
bool recvMessage(SOCKET sock, string& outMsg) {
    uint32_t netLen;
    int ret = recv(sock, (char*)&netLen, sizeof(netLen), 0);
    if (ret != sizeof(netLen)) return false;
    uint32_t len = ntohl(netLen);
    if (len == 0) { outMsg.clear(); return true; } // 空消息
    if (len > 10 * 1024 * 1024) return false; // 安全限制:10MB
    outMsg.resize(len);
    size_t received = 0;
    while (received < len) {
        int r = recv(sock, &outMsg[0] + received, len - received, 0);
        if (r <= 0) return false;
        received += r;
    }
    return true;
}

// 发送完整消息(长度头+内容)
bool sendMessage(SOCKET sock, const string& msg) {
    uint32_t len = (uint32_t)msg.size();
    uint32_t netLen = htonl(len);
    if (send(sock, (char*)&netLen, sizeof(netLen), 0) != sizeof(netLen)) return false;
    if (len > 0 && send(sock, msg.c_str(), len, 0) != (int)len) return false;
    return true;
}

void userHandler(SOCKET sock) {
    while (true) {
        string msg;
        if (!recvMessage(sock, msg)) break;
        // 获取用户名
        string username;
        {
            lock_guard<mutex> lock(mtx);
            auto it = userMap.find(sock);
            if (it == userMap.end()) break;
            username = it->second;
        }
        string fullMsg = username + ": " + msg;
        // 广播给所有其他客户端
        lock_guard<mutex> lock(mtx);
        for (SOCKET s : socks) {
            if (s == sock) continue;
            sendMessage(s, fullMsg);
        }
    }
    // 清理
    {
        lock_guard<mutex> lock(mtx);
        auto it = find(socks.begin(), socks.end(), sock);
        if (it != socks.end()) socks.erase(it);
        userMap.erase(sock);
        clientAddrMap.erase(sock);
        connectTimeMap.erase(sock);
    }
    closesocket(sock);
}

int main() {
    WSADATA wsa_data;
    WSAStartup(MAKEWORD(2, 2), &wsa_data);

    SOCKET listenSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (listenSock == INVALID_SOCKET) {
        cerr << "socket创建失败" << endl;
        return -1;
    }

    sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    cout << "请输入服务器监听端口:";
    cin >> port;
    server_addr.sin_port = htons(port);

    if (bind(listenSock, (sockaddr*)&server_addr, sizeof(server_addr)) == SOCKET_ERROR) {
        cerr << "端口绑定失败,请换一个端口" << endl;
        system("pause");
        return -1;
    }

    listen(listenSock, 100);

    vector<string> ips = getLocalIPs();
    cout << "\n服务器已启动,监听端口 " << port << endl;
    cout << "本机IP地址:" << endl;
    for (const string& ip : ips)
        cout << "  " << ip << endl;
    cout << "等待客户端连接...\n" << endl;

    while (true) {
        sockaddr_in client_addr;
        int client_addr_len = sizeof(client_addr);
        SOCKET clientSock = accept(listenSock, (sockaddr*)&client_addr, &client_addr_len);
        if (clientSock == INVALID_SOCKET) continue;

        // 接收用户名(以'\0'结尾,保持原样)
        char username[256] = {0};
        int recvLen = recv(clientSock, username, sizeof(username) - 1, 0);
        if (recvLen <= 0) {
            closesocket(clientSock);
            continue;
        }
        username[recvLen] = '\0';
        string uname(username);

        bool acceptUser = false;
        {
            lock_guard<mutex> lock(mtx);
            if (isValidUsername(uname)) {
                bool duplicate = false;
                for (const auto& p : userMap) {
                    if (p.second == uname) { duplicate = true; break; }
                }
                if (!duplicate) acceptUser = true;
            }
        }

        if (acceptUser) {
            char response = 1;
            send(clientSock, &response, 1, 0);
            string ip = inet_ntoa(client_addr.sin_addr);
            int port = ntohs(client_addr.sin_port);
            char ipPort[64];
            sprintf(ipPort, "%s:%d", ip.c_str(), port);
            time_t now = time(nullptr);
            {
                lock_guard<mutex> lock(mtx);
                socks.push_back(clientSock);
                userMap[clientSock] = uname;
                clientAddrMap[clientSock] = ipPort;
                connectTimeMap[clientSock] = now;
            }
            char* timeStr = ctime(&now);
            if (timeStr) {
                size_t len = strlen(timeStr);
                if (len > 0 && timeStr[len-1] == '\n') timeStr[len-1] = '\0';
                cout << "[连接] " << ipPort << " 用户名: " << uname << " 时间: " << timeStr << endl;
            }
            thread t(userHandler, clientSock);
            t.detach();
        } else {
            char response = 0;
            send(clientSock, &response, 1, 0);
            closesocket(clientSock);
        }
    }

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