2012-03-28 158 views
1

我对这篇博客不熟悉,虽然我在这里找到了很多答案。 我是在工作的Linux机器上安装的旧版tcl,它不支持IPv6。 我需要使用tcl测试一些IPv6功能,并且需要打开IPv6套接字。 我开始使用python,但我的问题是在tcl和python之间来回传递。在python和tcl之间发送和接收数据

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

我试图使用fileevent和vwait,但它没有奏效。有没有人以前做过?

+0

检查此:http://stackoverflow.com/questions/267420/tcl-two-way-communication-between-threads-in-windows 这是关于TCL <-> TCL通信,但我认为你应该能够适应它到TCL <-> Python通信 – stanwise 2012-03-28 19:36:44

+3

我会添加明显的,幽默的答案......使用Python作为代理,在Python中打开IPv4服务器套接字,使用Tcl连接它,并通过IPv6将其从Tcl中获得的内容发送出去。 – RHSeeger 2012-03-28 21:10:09

+0

是否可以使用Tcl 8.6b2?这应该支持IPv6(我认为这是由b2完成的......) – 2012-03-29 14:46:48

回答

0

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客户端:

$ 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 
服务器

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 "" 
} 

输出