Hey DW.
I'm trying to figure out a way so my TCP Server and client can seamlessly send messages back and forth without having to take turns sending the message.

Python isn't my language of choice but it's the one i have to use for this assessment.

I'm also using python 2.6.6

So far we have:

------------------------------------------------------------------------

# TCP server #
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("", 5000))
server_socket.listen(5)

print "TCPServer Waiting for client on port 5000"

while 1:
	client_socket, address = server_socket.accept()
	print "I got a connection from ", address
	while 1:
                data = raw_input ( "SEND( TYPE q or Q to Quit):" )
	 	if (data == 'Q' or data == 'q'):
			client_socket.send (data)
			client_socket.close()
			break;
		else:
			client_socket.send(data)
 
                data = client_socket.recv(512)
                if ( data == 'q' or data == 'Q'):
			client_socket.close()
			break;
		else:
			print "RECIEVED:" , data

------------------------------------------------------------------------

# TCP client 
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("localhost", 5000))
while 1:
    data = client_socket.recv(512)
    if ( data == 'q' or data == 'Q'):
        client_socket.close()
        break;
    else:
        print "RECIEVED:" , data
        data = raw_input ( "SEND( TYPE q or Q to Quit):" )
        if (data <> 'Q' and data <> 'q'):
            client_socket.send(data)
        else:
            client_socket.send(data)
            client_socket.close()
            break;

------------------------------------------------------------------------

Surely i can't be missing much code.
Thanks

-Marley

Edited 6 Years Ago by MarleyM: n/a

I was playing around with the same problem recently. The solution lies in threading. Basically you have a main loop and a secondary loop in a thread (for both the server and client). For example, the main loop can poll for received data whereas the threaded loop can wait for commands from the user. Hope this helps!

This article has been dead for over six months. Start a new discussion instead.