0

我正在使用 tcl 提供的 udp 包从一台电脑向另一台电脑发送 udp 数据包。在接收方,我创建了一个文件事件,这样只要 udp 端口​​上有数据,它就应该调用处理程序来读取数据。但是当我运行我的接收器脚本时,什么都没有发生,直到我在脚本中提到永远等待。我想要一个功能,只要 udp 端口​​上有数据,我就想读取它。请告诉我我该怎么做。这是我的发送者和接收者脚本。

名为“udp_sender_script.tcl”的发件人脚本:

namespace eval soc {
variable s
}

set soc::s [udp_open]
udp_conf $soc::s $IP_ADDR_RX  $UDP_PORT
fconfigure $soc::s -buffering none -translation binary

set data 1234
append hex [ format %04X [ expr $i | 0x8000 ] ]
append hex [ format %08X [ expr $data ] ]

while { 1 } {
after 500
puts -nonewline $soc::s [binary format H* $hex]
}

名为“udp_receiver_script.tcl”的 udp 脚本

proc udp_listen {} {
set pkt [read $soc::s ]
if { $pkt > 0 } {
puts "received string is $pkt"
}
return 0
}

proc every { ms body } {
eval $body; after $ms [info level 0]}

if { $argc < 1 } {
puts "ERROR! Please give udp port number as an argument while running the script"
} else {
set UDP_PORT [lindex $argv 0]
set  soc::s [udp_open $UDP_PORT]
fconfigure $soc::s -buffering none -translation binary
fileevent $soc::s readable [list ::udp_listen $soc::s]
}

如果我在接收器脚本的 while 循环中读取 udp 端口​​上的数据而不是使用 fileevent,我会得到数据。但我不会不必要地使用 while 循环。请帮我解决这个问题。

4

1 回答 1

2

除非您的第二个片段不是真正完整的,否则您会错过一个关键点:对于任何类型的事件,包括使用 设置的事件,fileeventTcl 运行时都必须“进入事件循环”。这暂停了使 Tcl 进入事件循环的脚本的执行,并且在响应生成的各种事件时才对 Tcl 代码进行进一步处理。当运行时离开事件循环时,将恢复正常处理。

在不使用 Tk 的程序中,通常使用vwait("wait for a variable until it'swritten") 命令进入事件循环,并且是这样完成。另请参阅内容并通常在 wiki中搜索“事件”关键字。

我还强烈推荐阅读“使用 Tcl 构建高性能网络服务器”

于 2013-01-21T07:58:13.893 回答