sockets - TCL 原始套接字多行响应
问题描述
我正在使用 TCL 作为语言的环境中编写测试代码。通过 raw socked 向设备发送命令后,我收到响应,有时是多行(设备终端不是很稳定)。
下面的代码只显示了一行。如果响应确实不止一行,如何轻松更改它以返回多行?
set connection [socket $session_ip $session_port]
puts $connection "my_command_here"
flush $connection
puts [gets $connection]
作为一种解决方法,我重复了最后两个步骤
flush $connection
puts [gets $connection]
不幸的是,如果只有一条线路响应,它就会冻结。尝试使用读取而不是获取但没有正确的结果。
解决方案
如果没有建立协议来确定响应中有多少行,则必须使用非阻塞输入。还建议使用基于事件的处理:
set connection [socket $session_ip $session_port]
# Set the connection to non-blocking and line buffering
fconfigure $connection -blocking 0 -buffering line
# Set up a proc to react to incoming events on the socket
# These can be: Receiving data and the connection being closed
fileevent $connection readable [list eventhandler $connection]
proc eventhandler {fd} {
if {[eof $fd]} {
puts "Remote side closed the connection"
close $fd
} elseif {[gets $fd line] != -1} {
puts $line
}
}
puts $connection "my_command_here"
vwait forever
使用基于事件的编程需要一种非常不同的方式来构建程序。这个主题太广泛了,无法在这里讨论。如果您不熟悉该概念,请在网络上查找更多信息。
推荐阅读
- c - OpenMP 并行乘法比顺序乘法慢
- java - 从双打列表创建坐标
- c# - 用于访问其他页面的文本框/对象的投射页面
- mysql - 想要统计出现次数,则只打印高于所有计数值平均值的计数值
- node.js - TypeError:无法读取未定义的 Graphql、Nodejs 的属性“forEach”
- angular - 如何以反应形式绑定表单输入值
- excel - 斜率和截距函数返回#Value!(错误 2015)
- firebase - 有没有办法知道文档是否已使用 firebase 函数添加到 firebase 的集合中
- c# - 当我想通过 C# 运行 GAMS 代码时,为什么 Visual Studio 会出现错误?
- java - 删除卡按钮单击 JavaFX