Hey,
Currently, I am trying to do a small project with sockets in Python, a two-user chatting system.
import socket
import threading
#Callback. Print doesn't work across threads
def data_recieved(data):
print data
#Thread class to gather input
class socket_read(threading.Thread):
sock = object
def __init__(self, sock):
threading.Thread.__init__(self)
self.sock = sock
def run(self):
while True:
data = self.sock.recv(1000)
if (data == "\quitting\\"):
return
data_recieved(self.sock.recv(1000))
####################################################################################
server = False
uname = input("What's your username: ")
print "Now for the technical info..."
port = input("What port do I connect to ['any' if first]: ")
#This is the first client. Let it get an available port
if (port == "any"):
server = True
port = 9999
err = True
while err == True:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', port))
err = False
except:
err = True
sock.close()
print "Bound to port #" + str(port)
print "Waiting for client..."
sock.listen(1)
(channel, info) = sock.accept()
else:
#This is the client. Just bind it tho a predisposed port
host = input("What's the IP of the other client: ")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, int(port)))
msg = ""
if (server == True):
#Use the connection from accept
reader = socket_read(channel)
else:
#Use the actual socket
reader = socket_read(sock)
reader.start()
while msg != 'quit':
#Get the message...
msg = uname + ": " + input("Message: ")
try:
#And send it
if (server == True):
#Use the connection from accept
channel.send(msg)
else:
#Use direct socket
sock.send(msg)
except:
break
reader.join()
channel.send("\quitting\\")
sock.close()
(I hope the comments help)
Anyhow, by calling for input at the same time, and getting the other socket's message, I've got a small syncronization issue. I can connect, but when I recieve a message, it doesn't cancel the input statement.
In other words, when I recieve a message, it says this
Message: user: I got a message
#Flashing cursor here
So that it doesn't cancel the input statement.
Also, I only get every other message.
Any suggestions?