多彩网猫聊天

Colorfull netcat chat

TLDR; 服务器端 nc -l PORT 这样所有客户端都可以看到特定颜色的服务器消息。

我可以打印红色文字:echo -e "\e[31mRed Message" 我能够将该文本通过管道传输到 netcat:echo -e "\e[31mRed Message" | nc -l 1234。这允许连接到我的用户看到红色消息(如果他们的终端支持颜色)。 但是我不知道如何在给定的 netcat 聊天会话中以特定颜色发送我的所有消息

echo -e "\e[31mRed Message" | nc -l 1234 的问题是只有一条消息以红色打印,然后服务器(侦听端口 1234 的机器)无法再发送消息。我正在寻找一种方法来不断重定向 stdin 并在通过 netcat 作为传出消息发送之前以不同的方式处理它(给它着色)。

通常 netcat 聊天可能是这样的:
服务器:nc -l 1234
客户:nc ${SERVER_IP} 1234

Hello I am the server
Hello I am a client
I am the server and my messages are boring and not colored
I am a client and my messages are equally boring

我最想做的是这个
服务器:some magic netcat thing that colors server text
客户:nc ${SERVER_IP} 1234

Hello I am the server
Hello I am a client
I am the server and my messages are cool and are all colored red!
I am a client and I can see your cool red colored messages, my messages are boring though :(

上例中用粗体表示红色文字

Good reference for bash coloring codes

如果我在服务器端使用它,这似乎对我有用:

#!/bin/bash

red="$(tput setaf 1)"
off="$(tput sgr0)"

while read line ; do
   printf "${red}${line}${off}\n"
done | nc -l 1234

完整解决方案,基于 KamilCuk 评论

服务器:

NO_COLOR="\x1b\[0m"      # Uncolored
SERVER_COLOR="\x1b\[31m" # Red

sed -u "s/^/${SERVER_COLOR}/g; s/$/${NO_COLOR}/g" | nc -l 1234 | sed "s/^/${NO_COLOR}/g; s/$/${SERVER_COLOR}/g"

客户:nc ${SERVER_IP} 1234

I am server.
I am client.
I see that I am red and you are uncolored.
I see that you are red. And I see that I am uncolored!
We see the same thing!

服务器:

NO_COLOR="\x1b\[0m"      # Uncolored
SERVER_COLOR="\x1b\[31m" # Red
CLIENT_COLOR="\x1b\[32m" # Green

sed -u "s/^/${SERVER_COLOR}/g; s/$/${NO_COLOR}/g" | nc -l 1234 | sed "s/^/${CLIENT_COLOR}/g; s/$/${SERVER_COLOR}/g"

客户:nc ${SERVER_IP} 1234

I am server
I am client
I see that I am red and you are green
I see that you are red, but I appear to be uncolored to myself
We see similar but different things

完成这项工作的技巧:

  1. netcat 进程的输入现在是 sed -u 进程的输出。 sed -u 进程得到 stdin
  2. netcat 进程的输出现在是 sed 进程的输入。这个 sed 过程就是生成 stdout 的过程。
  3. 两个 sed 脚本都使用 ^ 开头 添加颜色代码行和 $ 附加 颜色代码到行的 结束