python多线程服务器

我正在尝试编程的是一个简单的多线程
python游戏服务器,以获得乐趣.经过很多挫折之后,我无法弄清楚为什么我的测试客户端连接会超时.这是我的server.py代码:

    import socket
import threading
import clientThread
import struct
import string

class Server:
    def __init__(self):
        self.HOST = 'localhost'
        self.PORT = 22085
        self.BUFFIZE = 1024
        self.ADDRESS = (self.HOST,self.PORT)
        self.clientList = []
        input("Press enter to start the server. . .")
        self.running = True
        self.serverSock = socket.socket()
        self.serverSock.bind(self.ADDRESS)
        self.serverSock.listen(2)
        self.clientThread = clientThread.clientThread(self)
        print("Starting client thread. . .")
        self.clientThreadObj = threading.Thread(target = self.clientThread.start, args = (self))
        print("Awaiting connections. . .")
        while self.running:
            clientInfo = self.serverSock.accept()
            print("Client connected from %s." % clientInfo[1])
            # Append to clientThread list...

        self.serverSock.close()
        print("- end -")

serv = Server()

服务器启动现有连接的线程并开始侦听.为现有连接构建的线程clientThread循环遍历客户端对象列表,这些客户端对象现在什么也不做,它们只是架构.这是clientThread.py

import socket
import threading
import struct
import string

class clientThread:
    def __init__(self, serv):
        self.server = serv
        self.clientList = []
        self.running = True
        print("Client thread created. . .")
    def start(self):
        print("Beginning client thread loop. . .")
        while self.running:
            for client in self.clientList:
                message = client.sock.recv(self.server.BUFFSIZE)
                if message != None and message != "":
                    client.update(message)

最后,非常简单的客户端对象:

import string

class clientObject:
    def start(self,clientInfo):
        self.sock = clientInfo[0]
        self.address = clientInfo[1]
    def update(self,message):
        self.sock.send("Testamundo.\r\n".encode())

现在,这里的问题是我的客户端甚至无法连接到我的服务器.它只是超时.这是我的简单客户端测试的代码:

import socket
import string

address = ("192.168.1.1",22085)
mySocket = socket.socket()

mySocket.connect(address)
print("Connected successfully!")

这将在连接到地址的行上返回“连接尝试失败,因为连接方在一段时间后没有正确响应,或者由于连接主机未能响应而建立连接失败”.

有什么建议?谢谢!对不起所有这些代码,我不确定是否需要全部发布,所以我认为它不会伤害太多.

最佳答案 你有两个系统吗?服务器系统的IP是192.168.1.1吗?如果您只有一个系统,则localhost地址为127.0.0.1.这是我在同一系统上运行服务器和客户端时为了获得连接而对代码进行的第一次更改.

另一个问题是您的客户端线程实际上并未启动.既然你想要一个客户端线程类,这里是如何声明和启动它:

> threading.Thread的子类.
>为您的行为覆盖__init__,但首先在基类中调用__init__.
>覆盖线程工作的运行.
>创建一个实例并调用其start方法.

如果客户端没有发送任何数据,则另一个问题是recv阻塞,因此如果您尝试连接多个客户端,它将挂起在客户端列表上的循环中.您需要每个客户端一个线程或使用select.select查询客户端套接字的读/写准备情况.

下面是让单个客户端响应的更改代码,但它需要处理多个客户端.它还需要设置一个协议来处理消息. TCP是一种流媒体协议(没有消息边界),因此发送’abc’和’123’可能会导致接收’abc123’或’ab’和’c123’等.它必须处理关闭连接并从客户端列表中删除客户端对象.

祝好运!您将从头开始学习如何完成所有这些工作.查看socketserver.py库以及示例代码.

srv.py

import socket
import threading
import struct
import string

class clientThread(threading.Thread):
    def __init__(self, serv):
        threading.Thread.__init__(self)
        self.server = serv
        self.clientList = []
        self.running = True
        print("Client thread created. . .")
    def run(self):
        print("Beginning client thread loop. . .")
        while self.running:
            for client in self.clientList:
                message = client.sock.recv(self.server.BUFFSIZE)
                if message != None and message != "":
                    client.update(message)

class clientObject(object):
    def __init__(self,clientInfo):
        self.sock = clientInfo[0]
        self.address = clientInfo[1]
    def update(self,message):
        self.sock.send("Testamundo.\r\n".encode())

class Server(object):
    def __init__(self):
        self.HOST = 'localhost'
        self.PORT = 22085
        self.BUFFSIZE = 1024
        self.ADDRESS = (self.HOST,self.PORT)
        self.clientList = []
        input("Press enter to start the server. . .")
        self.running = True
        self.serverSock = socket.socket()
        self.serverSock.bind(self.ADDRESS)
        self.serverSock.listen(2)
        self.clientThread = clientThread(self)
        print("Starting client thread. . .")
        self.clientThread.start()
        print("Awaiting connections. . .")
        while self.running:
            clientInfo = self.serverSock.accept()
            print("Client connected from {}.".format(clientInfo[1]))
            self.clientThread.clientList.append(clientObject(clientInfo))

        self.serverSock.close()
        print("- end -")

serv = Server()

clnt.py

import socket
import string

address = ('localhost',22085)
mySocket = socket.socket()

mySocket.connect(address)
print("Connected successfully!")
mySocket.send('blah'.encode())
print(mySocket.recv(1024))

输出(srv.py)

Press enter to start the server. . .
Client thread created. . .
Starting client thread. . .
Beginning client thread loop. . .
Awaiting connections. . .
Client connected from ('127.0.0.1', 52850).

输出(clnt.py)

Connected successfully!
b'Testamundo.\r\n'
点赞