2012-03-28 156 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 "" 
} 

輸出