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;
}