首页 > 解决方案 > 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]

不幸的是,如果只有一条线路响应,它就会冻结。尝试使用读取而不是获取但没有正确的结果。

标签: socketstclresponsemultiline

解决方案


如果没有建立协议来确定响应中有多少行,则必须使用非阻塞输入。还建议使用基于事件的处理:

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

使用基于事件的编程需要一种非常不同的方式来构建程序。这个主题太广泛了,无法在这里讨论。如果您不熟悉该概念,请在网络上查找更多信息。


推荐阅读