【问题标题】:How do I create an update function in Batch?如何在 Batch 中创建更新函数?
【发布时间】:2017-10-25 15:40:50
【问题描述】:

我想创建一个更新功能,在提示用户输入“聊天框”后立即运行,以便我学校网络上的其他用户可以输入,并且所有其他用户都可以看到它,而无需重新启动程序或输入空格以重新加载 .txt 文件

这是我目前写的代码;

:enter
cls
type cblog.txt
echo.
set /p text=
echo %text% >> cblog.txt
goto enter

【问题讨论】:

  • batch 不支持进程间通信。也许你想使用different approach
  • 我建议你谷歌搜索批量聊天。你不是第一个这样做的人。

标签: batch-file


【解决方案1】:

我喜欢这个话题,所以我写了一个完整的原型:

@echo off
setlocal

if "%~1" equ "" echo You must give your username as parameter & goto :EOF

set "user=%~1"
set "now=%time%"
echo %now%: User %user% entered the chat room>> msgQueue.txt
call :chatRoom 3< msgQueue.txt
goto :EOF


:chatRoom

rem Omit previous messages
:omitMsg
   set /P "msg=" <&3
if "%msg:~0,12%" neq "%now%:" goto omitMsg
echo %msg%
echo/

echo Press S to send a message or eXit to end
echo/
:msgLoop

rem Check for new messages received
:showMsg
   set "msg="
   set /P "msg=" <&3
   if not defined msg goto send
   echo %msg%
goto :showMsg

rem Check to send a new message
:send
ver > NUL
choice /C SNX /N /T 3 /D N > NUL
if errorlevel 3 goto end
if errorlevel 2 goto msgLoop

rem Send a message
echo -----------------------------------
set /P "msg=Message: "
echo -----------------------------------
echo %user%: %msg% >> msgQueue.txt
goto msgLoop

:end
echo %time%: User %user% leaved the chat room>> msgQueue.txt

响应时间可以在choice命令的/T 3参数中调整:时间越短,聊天响应速度越快,但会消耗更多的CPU时间。

下图显示了在聊天室中对四个用户进行的测试:

【讨论】:

  • 程序似乎一打开就关闭了,我想这可能是因为您已声明“goto :EOF”,但您的代码中没有任何名称为 EOF
  • @callum - goto :eof 是一个系统命令,意思是“转到脚本的末尾”。
  • 你知道为什么你的代码一打开就关闭了吗?我需要下载一些东西才能让代码工作
  • 程序在这里正常工作;看我的编辑。我建议你先打开几个 cmd.exe Windows 并从那里执行批处理文件(not 通过在资源管理器中双击)。您是否阅读了You must give your username as parameter 消息?这意味着以这种方式执行批处理文件:test.bat YourNameHere 从命令行
猜你喜欢
  • 2015-01-19
  • 1970-01-01
  • 2019-11-29
  • 1970-01-01
  • 2022-08-16
  • 2015-05-06
  • 2018-10-15
  • 2015-07-06
  • 1970-01-01
相关资源
最近更新 更多