我已经学习了nc
一段时间了,我决定在 bash 中为其制作一个社交线程服务器。令人惊讶的是,我得到了它的工作,但我有一些问题。我想在这里解决的主要问题是如何通过发送线程和接收线程的注释一次只允许一个连接。由于我必须在发送线程和接收评论之间添加延迟,因此两个或更多客户端可以尝试同时接收和发送,这会破坏服务器。我想允许它在一个客户端请求线程时发送它,而不允许其他任何人能够连接。另一个问题是兼容性,因为存在不同版本的netcat。我在装有 BSD 的笔记本电脑上开发了这个程序nc
,当我在我的电脑上测试它时,它的工作方式与我的笔记本电脑上的工作方式不同,因为它具有不同版本的“nc”,并导致服务器卡住。如果有任何方法可以解决这个问题,或者有任何替代方法来实现我想要的,这对我来说真的很有帮助。
客户端代码:
#!/bin/bash
if [ "$1" == "" ]
then
echo "No IP selected."
exit 0
fi
if [ "$2" == "" ]
then
echo "No port selected."
exit 0
fi
if [ ! -e ~/.netthread ]
then
mkdir ~/.netthread
mkdir ~/.netthread/threads/
touch ~/.netthread/config
echo -n "Username: "
read name
echo $name >~/.netthread/config
fi
export ip=$1
export port=$2
getthread ()
{
echo "Getting thread..."
nc $ip $port >~/.netthread/threads/$ip:$port
sleep 1
nc $ip $port </dev/null
echo "Thread obtained!"
}
readthread ()
{
cat -s ~/.netthread/threads/$ip:$port | less +G
}
writethread ()
{
wow="$(cat ~/.netthread/config)"
touch /tmp/thread$$
chmod 700 /tmp/thread$$
echo "==============================" >> /tmp/thread$$
echo "User: $wow" >> /tmp/thread$$
echo -n "Date: " >> /tmp/thread$$
date >> /tmp/thread$$
echo "Press Ctrl-D to stop writing"
cat -s >> /tmp/thread$$
echo -e "\n" >> /tmp/thread$$
echo "==============================" >> /tmp/thread$$
echo "Sending comment..."
nc $ip $port >/dev/null
sleep 1
nc $ip $port </tmp/thread$$
echo "Comment sent!"
}
getthread
readthread
echo -n "Would you like to add a comment?(y/n): "
read lolz
if [ "$lolz" == "n" ]
then
exit 0
else
writethread
echo -n "Would you like to overview?(y/n): "
read over
if [ "$over" == "y" ]
then
getthread
readthread
fi
rm /tmp/thread$$
exit 0
fi
服务器代码(是的,这很愚蠢):
#!/bin/bash
while [ 1 ]
do
echo "send state"
sudo nc -l 22 < thread
echo "recive state"
sudo nc -l 22 >> thread
done