如何使用 Bash 制作 Echo 服务器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8375860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:17:09  来源:igfitidea点击:

How to make an Echo server with Bash?

bashtcpnetcat

提问by Roskoto

How to write a echo server bash script using tools like nc, echo, xargs, etc capable of simultaneously processing requests from multiple clients each with durable connection?

如何使用 nc、echo、xargs 等工具编写 echo 服务器 bash 脚本,这些工具能够同时处理来自多个具有持久连接的客户端的请求?

The best that I've came up so far is

到目前为止我提出的最好的是

nc -l -p 2000 -c 'xargs -n1 echo'

but it only allows a single connection.

但它只允许一个连接。

回答by David Costa

If you use ncat instead of nc your command line works fine with multiple connections but (as you pointed out) without -p.

如果您使用 ncat 而不是 nc 您的命令行可以在多个连接下正常工作,但(如您所指出的)没有 -p。

ncat -l 2000 -k -c 'xargs -n1 echo'

ncat is available at http://nmap.org/ncat/.

ncat 可从http://nmap.org/ncat/ 获得

P.S. with the original the Hobbit's netcat (nc) the -c flag is not supported.

PS 与原始霍比特人的 netcat (nc) 不支持 -c 标志。

Update: -k (--keep-open) is now required to handle multiple connections.

更新: -k (--keep-open) 现在需要处理多个连接。

回答by douyw

Here are some examples. ncat simple services

这里有些例子。ncat 简单服务

TCP echo server

TCP 回显服务器

ncat -l 2000 --keep-open --exec "/bin/cat"

UDP echo server

UDP 回显服务器

ncat -l 2000 --keep-open --udp --exec "/bin/cat"

回答by Caesar

In case ncat is not an option, socat will also work:

如果 ncat 不是一个选项,socat 也可以工作:

socat TCP4-LISTEN:2000,fork EXEC:cat

The forkis necessary so multiple connections can be accepted. Adding reuseaddrto TCP4-LISTENmay be convenient.

fork是必要的,因此可以接受多个连接。添加reuseaddrTCP4-LISTEN可能很方便。

回答by Mohan Nbs

what about...

关于什么...

#! /bin/sh

while :; do
/bin/nc.traditional -k -l -p 3342 -c 'xargs -n1 echo'
done