I am currently trying to execute a small socket project in Python, a dual user chat system.
import socket
import threading
def data_recieved(data):
print data
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 your username: ")
print "Now for the technical info..."
port = input("What port do I connect to ['any' if first]: ")
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:
host = input("What the IP of the other client: ")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, int(port)))
msg = ""
if (server == True):
reader = socket_read(channel)
else:
reader = socket_read(sock)
reader.start()
while msg != 'quit':
msg = uname + ": " + input("Message: ")
try:
if (server == True):
channel.send(msg)
else:
sock.send(msg)
except:
break
reader.join()
channel.send("\quitting\\")
sock.close()
(I hope the comments help)
In any case, causing simultaneous data input and receiving another socket message, I have a slight synchronization problem. I can connect, but when I receive a message, it does not cancel the input statement.
In other words, when I get a message, he talks about it
Message: user: I got a message
So it does not cancel the input statement.
In addition, I receive only every message.
Any suggestions?
source
share