我正在尝试使用python为一个小游戏创建一个简单的多人游戏模式 . 我想要做的是分享连接到服务器的每个玩家的位置 . 现在,虽然我很困难甚至有一个客户端与服务器通信,使用套接字模块和json文件(虽然似乎没有引起问题) .
The error I get and when:
一旦我尝试通过客户端第二次发送一些东西,我得到“[Errno 32] Broken pipe”错误 . 根据一些谷歌搜索,当连接关闭时会发生这种情况 . 不幸的是,我没有看到它被关闭的地方 .
目前我的代码非常多:http://thomasfischer.biz/python-simple-json-tcp-server-and-client/ . 自从我立刻遇到这个问题后,我没有太大变化 .
Server 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
1 回答
当连接的一端尝试发送数据而另一端已经关闭连接时,会发生Broken Pipe .
在尝试上述操作时,服务器已关闭连接 . 可能在
*lots of game related code*
期间,客户端TCP知道这一点 . 但是客户端应用程序不是 . 检查tcpdump b / w客户端和服务器 . 您应该从服务器看到FIN或RST .您需要具有捕获应用程序代码中的FIN / RST等TCP事件的机制 . 不应该使用捕获异步TCP事件的机制编写TCP应用程序 .