聊天/服务器客户端Python

时间:2015-04-20 18:02:31

标签: python python-3.x client chat server

我目前正在为大学做一个项目,我必须在python 3.4中创建一个多聊天客户端和服务器。 由于某种原因,它将连接到一个客户端,但当第二个客户端尝试连接时,它什么都不做。但是,当第一个客户端断开连接时,另一个客户端将连接到它。有没有人有任何想法,我一直试图解决这个问题超过3个小时。

客户端服务器

import socket

def Main():
    print("Send 'q' to exit\n")
    address = str(input("ip:port -> "))
    nick = input("nick: ")

    try:
        if address.index(":") != 0:
            host = address[:address.index(":")]
            port = int(address[address.index(":")+1:])
    except ValueError:
        host = address
        port = 5000

    s = socket.socket()
    s.connect((host, port))

    message = input("-> ")

    while message != "q":
        send_message = message + "pPp" + nick
        send_message2 = send_message.encode("UTF-8")
        s.send(bytes(send_message2))
        data = s.recv(1024)
        data_decoded = data.decode("UTF-8")
        data2 = data_decoded
        print(data_decoded)
        messageServer = str(data_decoded[:data_decoded.index("pPp")])
        nickServer = str(data_decoded[data_decoded.index("pPp")+3:])

        if not data_decoded == data2:
            print(nickServer + ": " + messageServer)
        message = input("-> ")
    s.close()

if __name__ == "__main__":
    Main()

服务器端:

import socket
import time
import os
from threading import Thread
folderPath = "Chat Logs"
filePath = folderPath + "/" + str(time.strftime("%H-%M-%S_%d-%m-%Y")) + ".txt"
def clientHandler(c):
    while True:
        data = c.recv(1024)
        if not data:
            break
        data_decoded = data.decode("UTF-8")
        message = str(data_decoded[:data_decoded.index("pPp")])
        nick = str(data_decoded[data_decoded.index("pPp")+3:])
        print(nick + "$" + message)
        saveChat(nick, message)
        print("   Sending: " + data_decoded)
        c.send(bytes(data_decoded.encode("UTF-8")))
    c.close()
def saveChat(nick, message):
    if not os.path.exists(folderPath):
        os.makedirs(folderPath)
    if not os.path.exists(filePath):
        f = open(filePath, "a")
        f.close()
    f = open(filePath, "a")
    f.write(nick + ": " + message + "\n")
    f.close()
def Main():
    host = str(socket.gethostbyname(socket.gethostname()))
    port = 5000
    print(host + ":" + str(port) + "\n")
    Clients = int(input("Clients: "))
    s = socket.socket()
    s.bind((host, port))
    s.listen(Clients)
    while True:
        c, addr = s.accept()
        print("Connection from: " + str(addr))
        Thread(target=clientHandler(c)).start()
    s.close()
if __name__ == "__main__":
    Main()

2 个答案:

答案 0 :(得分:1)

您正在正确初始化Thread对象。尝试其中之一:

    Thread(target=clientHandler, args=(c,)).start()

    Thread(target=lambda c=c: clientHandler(c)).start()

线程将{c}作为target参数。您的代码不是传入可调用的,而是调用clientHandler,并将其返回值传递给Thread.__init__

答案 1 :(得分:-1)

server.py的更改代码适合我。 如果我们接受线程处理程序中的连接并在调用处理程序时将套接字对象作为参数传递,那该怎么办呢?

def clientHandler(s):
    while True:
        c, addr = s.accept()
        print("Connection from: " + str(addr))
        data = c.recv(1024)
        if not data:
            break
        data_decoded = data.decode("UTF-8")
        message = str(data_decoded[:data_decoded.index("pPp")])
        nick = str(data_decoded[data_decoded.index("pPp")+3:])
        print(nick + "$" + message)
        #saveChat(nick, message)
        print("   Sending: " + data_decoded)
        c.send(bytes(data_decoded.encode("UTF-8")))
    c.close()

在main函数中,我更改了以下行。

while True:
    #c, addr = s.accept()
    #print("Connection from: " + str(addr))
    Thread(target=clientHandler(s)).start()

以下是连接结果:

>>> 
10.212.245.81:5000

Clients: 3
Connection from: ('10.212.245.81', 60945)
c1$hi
   Sending: hipPpc1
Connection from: ('10.212.245.81', 60976)
c2$hi
   Sending: hipPpc2
Connection from: ('10.212.245.81', 61096)
c3$hi
   Sending: hipPpc3

P.S我没有尝试通过超过客户端连接请求的数量来检查代码。