954,525 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Fluid Chat Server/Client

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

MarleyM
Newbie Poster
1 post since Nov 2010
Reputation Points: 10
Solved Threads: 0
 

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!

convoluted
Light Poster
26 posts since Sep 2010
Reputation Points: 12
Solved Threads: 1
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: