termchat: 极简双人终端聊天 (Node + TypeScript + Ink)
This commit is contained in:
+40
@@ -0,0 +1,40 @@
|
||||
#!/usr/bin/env node
|
||||
import { Command } from "commander";
|
||||
import { runUI } from "./ui.js";
|
||||
|
||||
const program = new Command();
|
||||
|
||||
program
|
||||
.name("chat")
|
||||
.description("极简双人终端聊天")
|
||||
.version("0.1.0");
|
||||
|
||||
program
|
||||
.command("serve")
|
||||
.description("作为服务端,等待对方连接")
|
||||
.option("-p, --port <number>", "监听端口", "9000")
|
||||
.option("-n, --name <name>", "你的昵称", "A")
|
||||
.action((opts) => {
|
||||
const port = Number(opts.port);
|
||||
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
|
||||
console.error(`无效端口:${opts.port}`);
|
||||
process.exit(1);
|
||||
}
|
||||
runUI({ role: "server", port, name: opts.name });
|
||||
});
|
||||
|
||||
program
|
||||
.command("connect <host>")
|
||||
.description("连接到对方")
|
||||
.option("-p, --port <number>", "端口", "9000")
|
||||
.option("-n, --name <name>", "你的昵称", "B")
|
||||
.action((host, opts) => {
|
||||
const port = Number(opts.port);
|
||||
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
|
||||
console.error(`无效端口:${opts.port}`);
|
||||
process.exit(1);
|
||||
}
|
||||
runUI({ role: "client", host, port, name: opts.name });
|
||||
});
|
||||
|
||||
program.parse();
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
import * as net from "node:net";
|
||||
import { createInterface } from "node:readline";
|
||||
|
||||
/** 消息:msg 为聊天消息,sys 为系统提示(仅本地显示,不走网络) */
|
||||
export interface ChatMessage {
|
||||
type: "msg" | "sys";
|
||||
/** 发送方昵称,sys 消息为空 */
|
||||
name: string;
|
||||
text: string;
|
||||
ts: number;
|
||||
}
|
||||
|
||||
export type Phase = "waiting" | "connected" | "closed";
|
||||
|
||||
export interface SessionHandlers {
|
||||
onMessage(m: ChatMessage): void;
|
||||
onPhase(phase: Phase): void;
|
||||
}
|
||||
|
||||
export interface SessionOptions {
|
||||
host?: string;
|
||||
port: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface Session {
|
||||
send(text: string): void;
|
||||
close(): void;
|
||||
readonly phase: Phase;
|
||||
}
|
||||
|
||||
/**
|
||||
* 建立一条双人会话:
|
||||
* - server: 监听端口,等对方连入(只接受第一个连接)
|
||||
* - client: 主动连接对方
|
||||
* 协议:每行一个 JSON
|
||||
*/
|
||||
export function createSession(
|
||||
role: "server" | "client",
|
||||
opts: SessionOptions,
|
||||
handlers: SessionHandlers
|
||||
): Session {
|
||||
let socket: net.Socket | null = null;
|
||||
let server: net.Server | null = null;
|
||||
let phase: Phase = "waiting";
|
||||
const queue: string[] = [];
|
||||
|
||||
const sys = (text: string): void =>
|
||||
handlers.onMessage({ type: "sys", name: "", text, ts: Date.now() });
|
||||
|
||||
const setPhase = (p: Phase): void => {
|
||||
if (phase === p) return;
|
||||
phase = p;
|
||||
handlers.onPhase(p);
|
||||
if (p === "connected") {
|
||||
for (const payload of queue.splice(0)) socket?.write(payload);
|
||||
}
|
||||
};
|
||||
|
||||
const wire = (sock: net.Socket): void => {
|
||||
socket = sock;
|
||||
const rl = createInterface({ input: sock });
|
||||
rl.on("line", (line) => {
|
||||
const s = line.trim();
|
||||
if (!s) return;
|
||||
try {
|
||||
handlers.onMessage(JSON.parse(s) as ChatMessage);
|
||||
} catch {
|
||||
// 兜底:对方发来的不是 JSON 就当纯文本
|
||||
handlers.onMessage({ type: "msg", name: "对方", text: s, ts: Date.now() });
|
||||
}
|
||||
});
|
||||
sock.on("error", (err) => sys(`连接出错:${err.message}`));
|
||||
sock.on("close", () => setPhase("closed"));
|
||||
};
|
||||
|
||||
if (role === "server") {
|
||||
server = net.createServer((sock) => {
|
||||
server?.close(); // 只接受第一个连入的人
|
||||
wire(sock);
|
||||
setPhase("connected");
|
||||
sys("对方已连入,开始聊天吧");
|
||||
});
|
||||
server.on("error", (err) => {
|
||||
sys(`监听失败:${err.message}`);
|
||||
setPhase("closed");
|
||||
});
|
||||
server.listen(opts.port, () => {
|
||||
sys(`等待对方连接 0.0.0.0:${opts.port} …`);
|
||||
});
|
||||
} else {
|
||||
const sock = net.connect({ host: opts.host ?? "127.0.0.1", port: opts.port });
|
||||
wire(sock);
|
||||
sock.on("connect", () => {
|
||||
setPhase("connected");
|
||||
sys(`已连接 ${opts.host}:${opts.port}`);
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
send(text: string): void {
|
||||
const payload =
|
||||
JSON.stringify({ type: "msg", name: opts.name, text, ts: Date.now() }) + "\n";
|
||||
if (phase === "connected") socket?.write(payload);
|
||||
else if (phase === "waiting") queue.push(payload);
|
||||
},
|
||||
close(): void {
|
||||
server?.close();
|
||||
socket?.end();
|
||||
setPhase("closed");
|
||||
},
|
||||
get phase(): Phase {
|
||||
return phase;
|
||||
},
|
||||
};
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
import React, { useEffect, useRef, useState } from "react";
|
||||
import { Box, Static, Text, render, useInput } from "ink";
|
||||
import { createSession, type ChatMessage, type Phase, type Session } from "./net.js";
|
||||
|
||||
export interface UIOptions {
|
||||
role: "server" | "client";
|
||||
host?: string;
|
||||
port: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export function runUI(opts: UIOptions): void {
|
||||
render(<App {...opts} />);
|
||||
}
|
||||
|
||||
function App({ role, host, port, name }: UIOptions) {
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
const [input, setInput] = useState("");
|
||||
const [phase, setPhase] = useState<Phase>("waiting");
|
||||
const sessionRef = useRef<Session | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const session = createSession(
|
||||
role,
|
||||
{ host, port, name },
|
||||
{
|
||||
onMessage: (m) => setMessages((prev) => [...prev, m]),
|
||||
onPhase: (p) => setPhase(p),
|
||||
}
|
||||
);
|
||||
sessionRef.current = session;
|
||||
return () => session.close();
|
||||
}, []);
|
||||
|
||||
useInput((ch, key) => {
|
||||
if (key.return) {
|
||||
const text = input.trim();
|
||||
if (!text || phase !== "connected") return;
|
||||
sessionRef.current?.send(text);
|
||||
setMessages((prev) => [
|
||||
...prev,
|
||||
{ type: "msg", name, text, ts: Date.now() },
|
||||
]);
|
||||
setInput("");
|
||||
} else if (key.backspace || key.delete) {
|
||||
setInput((prev) => prev.slice(0, -1));
|
||||
} else if (ch && !key.ctrl && !key.meta && !key.escape) {
|
||||
setInput((prev) => prev + ch);
|
||||
}
|
||||
});
|
||||
|
||||
const statusText =
|
||||
phase === "connected"
|
||||
? `已连接 · 你是「${name}」`
|
||||
: phase === "waiting"
|
||||
? role === "server"
|
||||
? `等待对方连接 0.0.0.0:${port} …`
|
||||
: `正在连接 ${host}:${port} …`
|
||||
: "连接已断开,按 Ctrl+C 退出";
|
||||
|
||||
const borderColor =
|
||||
phase === "connected" ? "green" : phase === "waiting" ? "yellow" : "red";
|
||||
|
||||
return (
|
||||
<>
|
||||
<Static items={messages}>
|
||||
{(m, i) => <Message key={`${m.ts}-${i}`} m={m} me={name} />}
|
||||
</Static>
|
||||
<Box borderStyle="round" borderColor={borderColor} paddingLeft={1} paddingRight={1}>
|
||||
<Text dimColor>{statusText}</Text>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text bold color="green">
|
||||
❯{" "}
|
||||
</Text>
|
||||
<Text>{input}</Text>
|
||||
<Text color="green">▌</Text>
|
||||
</Box>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Message({ m, me }: { m: ChatMessage; me: string }) {
|
||||
if (m.type === "sys") {
|
||||
return (
|
||||
<Text dimColor color="yellow">
|
||||
· {m.text}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
const mine = m.name === me;
|
||||
const time = new Date(m.ts).toLocaleTimeString("zh-CN", { hour12: false });
|
||||
return (
|
||||
<Text>
|
||||
<Text dimColor>{time} </Text>
|
||||
<Text bold color={mine ? "green" : "cyan"}>
|
||||
{mine ? "我" : m.name}:{" "}
|
||||
</Text>
|
||||
<Text>{m.text}</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user