0

谁能告诉我如何让我的代码并行工作,让客户立即看到其他发送的内容以及是否有人加入了聊天。(代码没有完成,因为当我看到函数“receive”和“startconnection”不能同时工作时我停止了)接收函数正在从客户端获取数据并将其发送给除了他自己之外的所有人。startconnection 函数开始与客户端的连接。我需要新的客户端始终能够连接服务器并从其他客户端发送和获取数据。

编码:

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()
4

0 回答 0