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!")
这在连接到地址的线路上返回,“连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立的连接失败,因为连接的主机未能响应” ”。
有什么建议吗?谢谢!对所有这些代码感到抱歉,我不确定是否需要将其全部发布,所以我认为它不会造成太大伤害。
What I'm trying to program is a simple multithreaded python game server for fun. After much frustration, I've not been able to figure out why my test client connection times out. Here's my server.py code:
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()
The server starts the thread for existing connections and starts listening. The thread built for existing connections, clientThread
, loops through a list of client objects which for now do nothing, they are simply architectural. Here is the 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)
And finally, the very simple client object:
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())
Now, the problem here is that my client can't even connect to my server. It simply times out. Here is the code for my simple client test:
import socket
import string
address = ("192.168.1.1",22085)
mySocket = socket.socket()
mySocket.connect(address)
print("Connected successfully!")
This returns on the line that connects to address, "A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond."
Any suggestions? Thanks! Sorry for all this code, I wasn't sure if I needed to post it all or not, so I figured it couldn't hurt too much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你有两个系统吗?服务器系统的IP是否为192.168.1.1?如果您只有一个系统,则本地主机地址为 127.0.0.1。这是我必须对代码进行的第一个更改,以便在同一系统上运行服务器和客户端时获得连接。
另一个问题是您的客户端线程实际上并未启动。由于您需要一个客户端线程类,因此声明和启动它的方法如下:
__init__
,但首先在基类中调用__init__
。run
。start
方法。另一个问题是如果客户端未发送任何数据,则
recv
会阻塞,因此如果您尝试连接多个客户端,它将挂在客户端列表上的循环中。您需要每个客户端一个线程,或者使用select.select
来查询客户端套接字的读/写准备情况。下面是更改后的代码,使单个客户端做出响应,但需要处理多个客户端。它还需要建立一个协议来处理消息。 TCP 是一种流协议(没有消息边界),因此发送“abc”和“123”可能会导致接收“abc123”或“ab”和“c123”等。它必须处理关闭连接并从客户端列表中删除客户端对象。
祝你好运!您将学到很多东西,了解如何从头开始完成这一切。另请查看
socketserver.py
库以及示例代码。srv.py
clnt.py
输出 (srv.py)
输出 (clnt.py)
Do you have two systems? Does the server system have an IP of 192.168.1.1? If you only have one system, the localhost address is 127.0.0.1. That was the first change I had to make to your code to get a connection when running the server and client on the same system.
Another issue is your client thread doesn't actually start. Since you want a client thread class, here's how to declare and start it:
__init__
for your behavior, but call__init__
in the base class first.run
for the thread work.start
method.Another problem is
recv
blocks if the client hasn't sent any data, so if you try to connect multiple clients it will hang in your loop over the client list. You'll need a thread per client or useselect.select
to query the client sockets for read/write readiness.Below is the changed code that got a single client to respond, but it needs work to handle multiple clients. It also needs to set up a protocol to handle messages. TCP is a streaming protocol (no message boundaries), so a send of 'abc' and '123' could result in a receive of 'abc123' or 'ab' and 'c123', etc. It'll have to handle closing the connections and remove the client objects from the client list as well.
Good luck! You'll learn a lot figuring out how to do all this from scratch. Look at the
socketserver.py
library as well for example code.srv.py
clnt.py
Output (srv.py)
Output (clnt.py)