Хочу сделать tcp-сервер. Основываюсь на примерах их документации. Код сервера:
| Код | # -*- coding: utf-8 -*-
import SocketServer from threading import Timer f = open( '1.out', 'w' ) class F(object): def __init__(self, f): self.f = f
def write(self, x): self.f.write(str(x)+"\n") self.f.flush() f = F(f)
class MySocket(object): connList = [] def __init__(self, socket): self.sock = socket self.connList.append(socket) data = socket.recv(1024).strip() socket.send(data.upper()) print self.connList
@classmethod def hello(cls): for conn in cls.connList: try: conn.send("11111111") except Exception, e: print repr(conn) if not cls.connList: f.write( "connList is empty" ) run()
@classmethod def temp(cls): MySocket.connList[0].send('000000')
def run(): t = Timer(2.0, MySocket.hello) t.start() run() t = Timer(4.0, MySocket.temp) t.start()
class MyTCPHandler(SocketServer.BaseRequestHandler): def handle(self): MySocket(self.request)
HOST, PORT = "", 9999 server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler) server.serve_forever() |
Код клиента:
| Код | # -*- coding: utf-8 -*- import socket HOST, PORT = "localhost", 9999 data = "hello from Python client" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((HOST, PORT))
x = '1' sock.send(data + "\n") while 1: received = sock.recv(1024) if received: print "Received: %s" % received
sock.close() |
сначала запускаю файл сервера, потом код клиента. клиент отображает: Received: HELLO FROM PYTHON CLIENT
потом срабатывает таймер и на "сервере" возникает ошибка:
| Код | Exception in thread Thread-2: Traceback (most recent call last): File "C:\python25\lib\threading.py", line 486, in __bootstrap_inner self.run() File "C:\python25\lib\threading.py", line 663, in run self.function(*self.args, **self.kwargs) File "Server.py", line 27, in hello conn.send("11111111") File "C:\Python25\lib\socket.py", line 141, in _dummy raise error(EBADF, 'Bad file descriptor') error: (9, 'Bad file descriptor') |
на сколько понимаю, ошибка в том, что соединение закрылось. не понимаю, почему оно закрылось. как сделать, чтобы оно осталось открытым? |