gcham
gcham

Reputation: 11

Sending and receiving data between python and tcl

I am new to this blog when it comes to posting, although I have found many answers here. I am an older version of tcl installed on the linux box at work and it doesn't support IPv6. I need to test some IPv6 features using tcl, and need to open IPv6 sockets. I proceeded to do so using python, but my problem is communicating back and forth between tcl and python.

I implemented a server on Python and a client that talks to that server on tcl. The problem I am facing is the ability to do the following from tcl: read from python --> write to python --> read from python --> write to python...... (you get the point)

I tried to do using fileevent and vwait, but it didn't work. Has anyone done that before?

Upvotes: 1

Views: 3168

Answers (1)

E.Z.
E.Z.

Reputation: 6661

Python server:

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 client:

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

Output of the server:

$ 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

Output of the client:

$ 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

Upvotes: 1

Related Questions