使用聊天服务器进行线程处理Python 3

时间:2017-05-19 10:34:38

标签: python multithreading python-3.x python-multithreading

我有一个问题,如果我尝试解决它,它没有任何帮助这个问题。我正在尝试在端口5000为localhost创建一个聊天服务器。我有一个客户端和一个具有大部分逻辑的serverTCP。

import socket
from _thread import *
from queue import Queue
import threading

def main():
    try:
        host = 'localhost'
        port = 5000
        s = socket.socket()
        s.bind((host,port))
        s.listen(10)
        #Listens for incomming connections
        c, addr = s.accept()
        print("Connection from: " + str(addr))
        while True:
            data = c.recv(1024).decode('utf-8')
            if not data:
                break
            print("From connected %s: " %(str(addr)) + data)
            #data = data.upper()
            forma = '[' + str(addr) + '] ' + data
            #Undo The bellow comments if system malfunction
            #tosend = input(str("-->"))
            #print("Sending: " + tosend)
            #c.send(tosend.encode('utf-8'))
            c.send(forma.encode('utf-8'))

        print("Connection was lost with: " + str(addr))

        main()
    except ConnectionResetError as CRE:
        print(str(CRE))
        main()

    except ConnectionAbortedError as CAE:
        print(str(CAE))
        main()

    except OSError as OSE:
        print(str(OSE))
        return
    main()

def threader():
    while True:
        worker = q.get()
        main()
        q.task_done()

q = Queue()

mtfu_l = threading.Lock()
for x in range(10):
    t = threading.Thread(target = threader)
    t.daemon = True
    t.start()

for worker in range(20):
    q.put(worker)

q.join()

而且,客户一:

import socket
from threading import Thread
inp = input("client num?")
inp2 = input("Name?")
host='localhost'

port=5000

def main(host,port):
    try:
        headers = {}
        headers['User-Agent'] = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"
        s = socket.socket()
        s.connect((host,port))
        print('connection established with ' + host) 
        connect = True
        while connect:
            message = input("--> ")
            ss = socket.socket()
            ss.connect((host,port))
            config = '[' + inp2 + ']' + message + ' '
            while message != 'q':
                s.send(config.encode('utf-8'))
                data = s.recv(1024).decode('utf-8')
                print(data)
                message = input("--> ")
                config = '[' + inp2 + ']' + message + ' '
            print('Connection was lost with ' + host)
            connect = False
        if connect != True:
            main(host,port)
    except BaseException as BE:
        print(BE)
print('Connection lost with ' + host)
main(host,port)

我的问题是,我不能让多个用户互相聊天。我希望情况如此。我尝试过线程并将多个函数链接在一起,但似乎没有任何效果。我认为你们堆栈的人可以帮助我。

谢谢, 杰里

1 个答案:

答案 0 :(得分:0)

您只能将一个进程/事物绑定到端口。您需要弄清楚如何将各个连接路由到给定的处理程序。