2012-05-08 4 views
1

я получаю это:Ошибка при отключении от сервера

Traceback (most recent call last): 
    File "C:\Users\T_Mac\Desktop\Rex's Stuff\PyNet\Client.py", line 14, in <module 
> 
    server.connect(ADDRESS) 
    File "C:\Python27\lib\socket.py", line 224, in meth 
    return getattr(self._sock,name)(*args) 
    File "C:\Python27\lib\socket.py", line 170, in _dummy 
    raise error(EBADF, 'Bad file descriptor') 
socket.error: [Errno 9] Bad file descriptor 

Когда я бегу 'changeclient' с этим кодом, как мой сервер:

# Server 

from socket import * 

PORT = 5000 
BUFSIZE = 1024 
ADDRESS = ('', PORT)  # '' = all addresses. 
server = socket(AF_INET, SOCK_STREAM) 

server.bind(ADDRESS) 
server.listen(5) 
# print stuff the user needs to know 
print '' 
print ' ____    _____  ___ _______ ' 
print '/ \ |  |/ \ /____\  |  ' 
print '|  | |  | |  | |   |  ' 
print ' \____/ \____/| |  | \____/  | v0.1' 
print ' |    |        ' 
print ' |    |        ' 
print ' |    |        ' 
print ' |  _____/        ' 
print 'Contact Rex for any bug reports at [email protected]' 
print '\n' 
print 'Please input the command when prompted with \'>\'' 
print 'The stdout stuff will be in this format: ' 
print '  (<stdout>, <stderr>)\n' 

while True: 
    END_SCRIPT = 0           #Setting command to something other than '1' 
    print '\nWaiting for connections...' 
    client, address = server.accept() 
    print '...client connected from ', address[0], '\n' 
    while True: 
     command = raw_input('> ') 
     if command == 'quit': 
      server.close() 
      END_SCRIPT = 1 
      break 
     elif command == 'exit': 
      server.close() 
      END_SCRIPT = 1 
      break 
     elif command == 'changeclient': 
      print 'Changing clients.....\n' 
      client.send(command) 
      break 
     else: 
      client.send(command) 
      commandJazz = client.recv(BUFSIZE) 
      print commandJazz 
    if END_SCRIPT == 1: 
     print 'Closing server......' 
     print 'Goodbye!' 
     break 
server.close() 

И это как мой Клиент:

# client 

from subprocess import * 
from socket import * 
import time 
test = 0 
PORT = 5000 
IP = 'localhost'  #To change it to your ip, delete 'raw_input('> ')' and put your IP in its place. 
BUFSIZE = 1024 
ADDRESS = (IP, PORT) 
server = socket(AF_INET, SOCK_STREAM) 

while True: 
    server.connect(ADDRESS) 
    while True: 
     command = server.recv(BUFSIZE) 
     if command == 'changeclient': 
      server.close() 
      test = 1 
      break 
     else: 
      executeIt = Popen(command, shell = True, stdin = PIPE, stdout = PIPE, stderr = STDOUT) 
      commandJazz = executeIt.communicate() 
      strCommandJazz = str(commandJazz) 
      server.send(strCommandJazz) 

Я запускаю свой сервер, а затем запускаю два экземпляра моего клиента. Он прекрасно соединяется, и все работает нормально. Я создал команду под названием changeclient для отключения текущего клиента и подключения к другому. Всякий раз, когда я выполняю changeclient, я получаю ранее опубликованную ошибку на моем клиенте.

ответ

1

Когда вы закрываете гнездо, не используйте его повторно. Создайте новый:

server = socket(AF_INET, SOCK_STREAM) 
server.connect(ADDRESS) 

Прямо сейчас вы пытаетесь подключиться к одному экземпляру сокета.

Вы также можете попытаться использовать флаг, который указывает сокету повторно использовать порт при его повторном открытии вместо создания нового.

server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 
Смежные вопросы