我阅读了fileevent和fconfigure示例,并能够使回显服务器正常工作。我需要一些有关如何修改它的指示,以便每当客户端连接到服务器时,我就可以使服务器每10秒写入一次通道。
最终,我希望客户端处理连续的数据流。
服务器:
proc accept {chan addr port} {
global echo
puts "connection accepted from $addr:$port"
set echo(addr,$chan) [list $addr $port]
fconfigure $chan -buffering line
fileevent $chan readable [list Echo $chan]
}
proc Echo {sock} {
global echo
if {[eof $sock] || [catch {gets $sock line}]} {
close $sock
puts "Close $echo(addr,$sock)"
unset echo(addr,$sock)
} else {
puts $sock $line
puts $line
}
}
set s [socket -server accept 12345]
vwait forever
此服务器将接受连接并回显客户端写入通道的所有内容。
客户:
set conn [socket localhost 12345]
fconfigure $conn -buffering line
puts $conn "Hello world"
答案 0 :(得分:1)
了解要实现的协议是正确设置套接字服务器的关键。就您而言,如果您每隔10秒钟编写一条消息,而不是听客户端的消息,则您的代码将变为:
angular.json
当然,如果您使用的是Tcl 8.6,则可以写得更清晰一些:
import * as $ from 'jquery';
答案 1 :(得分:0)
Server.tcl
proc accept {chan addr port} {
global echo
puts "connection accepted from $addr:$port"
set echo(addr,$chan) "$chan - [list $addr $port]"
fconfigure $chan -buffering line
fileevent $chan readable [list Echo $chan]
}
proc Echo {sock} {
global echo
if {[eof $sock] || [catch {gets $sock line}]} {
catch {close $sock}
puts "Close $echo(addr,$sock)"
unset echo(addr,$sock)
} else {
set line [string trim $line]
if {$line eq {}} {
catch {close $sock}
puts "Close $echo(addr,$sock)"
unset echo(addr,$sock)
return
}
puts "Received '$line' from Client $echo(addr,$sock)"
puts "Waiting for 10 seconds"
after 10000
set serverResp [expr {$line+1}]
puts "Sending '$serverResp' to Client"
puts $sock $serverResp
}
}
set s [socket -server accept 12345]
puts "Server started on port 12345"
vwait forever
Client.tcl
set conn [socket localhost 12345]
fconfigure $conn -buffering line
fileevent $conn readable [list Echo $conn]
# Client starts the communication
puts "Sending '0' to Server"
puts $conn "0"
proc Echo {sock} {
if {[eof $sock] || [catch {gets $sock line}]} {
catch {close $sock}
puts "Unable to read data from server. So, client is exiting..."
exit 1
} else {
set line [string trim $line]
if {$line eq {}} {
puts "Unable to read data from server. So, client is exiting..."
exit 1
}
puts "Received '$line' from Server"
set clientResp [expr {$line+1}]
puts "Sending '$clientResp' to Server"
puts $sock $clientResp
}
}
vwait forever