在python和tcl之间发送和接收数据

时间:2012-03-28 19:31:00

标签: python tcl

在发布时,我是这个博客的新手,虽然我在这里找到了很多答案。 我是工作时在linux机器上安装的旧版本的tcl,它不支持IPv6。 我需要使用tcl测试一些IPv6功能,并且需要打开IPv6套接字。 我继续使用python这样做,但我的问题是在tcl和python之间来回沟通。

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

我尝试使用fileevent和vwait,但它没有用。有人曾经这样做过吗?

1 个答案:

答案 0 :(得分:1)

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