Can someone tell me how to make my code work in parallel , that the client see immediately what other sent and if someone joined the chat . (the code isn't finished because I stopped when I saw the function "receive" and "startconnection" doesn't work in the same time) the receive function is getting data from the client and sending it to everyone except himself . the startconnection function start connection with clients. I need that new will client always be able to connect the server and send and get data from other clients.
The Code:
import socket
import threading
import time
add=[]
d=[]
i=0
def startconnection():
time.sleep(0.6)
server_socket.listen(1)
(client_socket,client_address)=server_socket.accept()
print "new client has connected"
if i!=0:
sendall("new client connected",i)
global d
global add
global i
add=add+[client_address]
d=d+[client_socket]
i+=1
x=True
def receive(tmp):
time.sleep(0.6)
global x
global i
global d
print "I am here again working with client number: %d ,the numbers of
connected clients are : %d" %(tmp,i)
data=d[tmp].recv(1024)
if data!= "":
print "needs to send everyone exept the sender this data: %s" %
(data)
sendall(data,findplace(d[tmp]))
print "Finish working with client"
def sendall(text,nottosend):
print "got to sendall"
global i
global d
tp=0
while tp<i:
if tp!=nottosend:
d[tp].send(text)
tp+=1
def run():
global i
thread = threading.Thread(target=startconnection())
thread.daemon = True
thread.start()
time.sleep(0.6)
b=0
while i != 0 and b<=i-1:
time.sleep(0.6)
thread = threading.Thread(target=receive(b)).start()
b+= 1
def findplace(client_socket):
global d
i=0
while i<len(d):
if client_socket==d[i]:
return i
else:
i+=1
print "!!!!!!!!!!!Eror in findplace!!!!!!!!!!!"
return -1
if __name__ == '__main__':
server_socket = socket.socket()
server_socket.bind(('127.0.0.1', 231))
while x:
thread = threading.Thread(target=run())
thread.daemon = True
thread.start()