我正在尝试使用 python 为一个小游戏创建一个简单的多人游戏模式。我想要做的是共享连接到服务器的每个玩家的位置。现在,尽管我一直在努力让一个客户端与服务器通信,使用套接字模块和 json 文件(虽然这似乎不会引起问题)。
我得到的错误和时间:
当我第二次尝试通过客户端发送内容时,我收到“[Errno 32] Broken pipe”错误。根据一些谷歌搜索,当连接关闭时会发生这种情况。不幸的是,我看不到它在哪里关闭。
目前我的代码几乎是这样的:http://thomasfischer.biz/python-simple-json-tcp-server-and-client/ .自从我立即遇到这个问题后,我并没有做太多改变。
服务器客户端:
import SocketServer
import json
class MyTCPServer(SocketServer.ThreadingTCPServer):
allow_reuse_address = True
class MyTCPServerHandler(SocketServer.StreamRequestHandler):
def handle(self):
try:
data = json.loads(self.request.recv(1024).strip())
print data
except Exception, e:
print "Exception wile receiving message: ", e
server = MyTCPServer(('127.0.0.1', 13373), MyTCPServerHandler)
server.serve_forever()
玩家客户端:
import SocketServer
import json
def __init__(self):
self.S = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.S.connect(('127.0.0.1', 13373))
*lots of game related code*
pos = {'id':id, 'pos': (x, y, z)}
self.S.send(json.dumps(pos))
self.position = (x, y, z)
if __name__ == '__main__':
main() #to keep the game running and updating
错误:
File "/usr/local/lib/python2.7/dist-packages/pyglet/app/__init__.py", line 123, in run
event_loop.run()
File "/usr/local/lib/python2.7/dist-packages/pyglet/app/base.py", line 135, in run
self._run_estimated()
File "/usr/local/lib/python2.7/dist-packages/pyglet/app/base.py", line 164, in _run_estimated
timeout = self.idle()
File "/usr/local/lib/python2.7/dist-packages/pyglet/app/base.py", line 273, in idle
redraw_all = self.clock.call_scheduled_functions(dt)
File "/usr/local/lib/python2.7/dist-packages/pyglet/clock.py", line 309, in call_scheduled_functions
item.func(ts - item.last_ts, *item.args, **item.kwargs)
File "/home/tim/tools/Pyglet/PlayerClient.py", line 609, in update
self._update(dt / m)
File "/home/tim/tools/Pyglet/PlayerClient.py", line 641, in _update
self.S.send(json.dumps(pos))
socket.error: [Errno 32] Broken pipe
最佳答案
当连接的一端尝试发送数据而另一端已经关闭连接时,就会发生 Broken Pipe。
self.S.send(json.dumps(pos))
当尝试上述操作时,服务器已经关闭了连接。可能在 *很多游戏相关代码*
期间,客户端 TCP 知道这一点。但客户端应用程序不知道。检查 tcpdump b/w 客户端和服务器。您应该从服务器看到 FIN 或 RST。
您需要有一种机制来在您的应用程序代码中捕获 TCP 事件,例如 FIN/RST。不应该在没有捕获异步 TCP 事件的机制的情况下编写 TCP 应用程序。
关于python - TCP 服务器/客户端 : [Errno 32] Broken pipe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28021928/