尽管我在这里找到了很多答案,但对于发布这个博客我还是陌生的。
我是在工作的Linux机器上安装的tcl的较旧版本,它不支持IPv6。
我需要使用tcl测试一些IPv6功能,并且需要打开IPv6套接字。
我继续使用python进行操作,但是我的问题是tcl和python之间来回通信。

我在Python上实现了服务器,并在tcl上实现了与该服务器通信的客户端。
我面临的问题是从tcl执行以下操作的能力:
从python读取->写入python->从python读取->写入python ......(你明白了)

我尝试使用fileevent和vwait进行操作,但是没有用。有人做过吗?

最佳答案

Python服务器:

import socket
host = ''
port = 45000
s = socket.socket()
s.bind((host, port))
s.listen(1)
print "Listening on port %d" % port
while 1:
    try:
        sock, addr = s.accept()
        print "Connection from", sock.getpeername()
        while 1:
            data = sock.recv(4096)
            # Check if still alive
            if len(data) == 0:
                break
            # Ignore new lines
            req = data.strip()
            if len(req) == 0:
                continue
            # Print the request
            print 'Received <--- %s' % req
            # Do something with it
            resp = "Hello TCL, this is your response: %s\n" % req.encode('hex')
            print 'Sent     ---> %s' % resp
            sock.sendall(resp)
    except socket.error, ex:
        print '%s' % ex
        pass
    except KeyboardInterrupt:
        sock.close()
        break


TCL客户端:

set host "127.0.0.1"
set port 45000
# Connect to server
set my_sock [socket $host $port]
# Disable line buffering
fconfigure $my_sock -buffering none
set i 0
while {1} {
    # Send data
    set request "Hello Python #$i"
    puts "Sent     ---> $request"
    puts $my_sock "$request"
    # Wait for a response
    gets $my_sock response
    puts "Received <--- $response"
    after 5000
    incr i
    puts ""
}


服务器的输出:

$ python python_server.py
Listening on port 45000
Connection from ('127.0.0.1', 1234)
Received <--- Hello Python #0
Sent     ---> Hello TCL, this is your response: 48656c6c6f20507974686f6e202330

Received <--- Hello Python #1
Sent     ---> Hello TCL, this is your response: 48656c6c6f20507974686f6e202331


客户端输出:

$ tclsh85 tcl_client.tcl
Sent     ---> Hello Python #0
Received <--- Hello TCL, this is your response: 48656c6c6f20507974686f6e202330

Sent     ---> Hello Python #1
Received <--- Hello TCL, this is your response: 48656c6c6f20507974686f6e202331

关于python - 在python和tcl之间发送和接收数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9914393/

10-09 16:44
查看更多