2017-11-06 4 views
0

어떤 이유로 인해 다음 기본 프로그램은 두 번째 시간부터 클라이언트를 서버에 연결합니다. 그리고 매번 서버를 다시 시작해야합니다. 누군가가이 행동의 이유와이 문제를 해결하는 방법을 설명 할 수 있습니까? asyncore가 서버 측에서만 사용되기 때문일 수 있습니다. (Windows 7, Python 3) 미리 감사드립니다!Python 클라이언트 - 서버 응용 프로그램이 연결되지 않습니다.

Сlient :

import socket 
sock = socket.socket() 
host = 'localhost' 
port = 8081 
tempr = port 
sock.connect((host,port)) 

서버 :

import asyncore 
import socket 
import time 

class EchoHandler(asyncore.dispatcher_with_send): 

def handle_read(self): 
    data = self.recv(1024) 

class EchoServer(asyncore.dispatcher): 
    def __init__(self, host, port): 
    asyncore.dispatcher.__init__(self) 
    self.create_socket(socket.AF_INET, socket.SOCK_STREAM) 
    self.set_reuse_addr() 
    self.bind((host, port)) 
    self.listen(2) 

    def handle_accept(self): 
    pair = self.accept() 
    if pair is not None: 
     sock, addr = pair 
     print ('Incoming connection from %s' % repr(addr)) 
     handler = EchoHandler(sock) 

def main(): 
    host = 'localhost' 
    port = 8081 
    server = EchoServer(host, port) 

    print ('Server %s running'% port) 
    asyncore.loop() 

if __name__ == '__main__': 
    main() 
+0

무슨 에러가 발생합니까? –

+0

오류 및 예외는 없지만 handle_accept() 함수는 두 번째 클라이언트 연결 시도에서만 실행됩니다. – Viktor

+0

필자는 문서에서 벗어나서'asyncore'에 익숙하지 않았지만'handle_except'에서'accept'를 호출해서는 안된다고 생각합니다. 서버는 연결을 수락 한 후 해당 함수를 호출 할 수 있으므로 중복 될 수 있습니다. –

답변

0

socket의 요점은 send()recv()에 대한 클라이언트와 서버 사이의 데이터 (수신). 서버에 연결 한 후 일부 데이터 (심지어는 빈 문자열이 전송되어야 함)를 서버에 보내야하며 서버는 클라이언트에 일부 데이터를 반환하거나 연결을 닫을 수 있습니다.

my_client.py

import socket 

sock = socket.socket() 
sock.connect(('localhost', 8081)) 
sock.send(b'data from client') 
print(sock.recv(32)) 
sock.close() 

my_server.py

import asyncore 
import socket 
import time 


class EchoHandler(asyncore.dispatcher_with_send): 
    def handle_read(self): 
     data = self.recv(1024) 
     print('data from client', data) 
     self.send(b'data from server') 
     self.close() 


class EchoServer(asyncore.dispatcher): 
    def __init__(self, host, port): 
     asyncore.dispatcher.__init__(self) 
     self.create_socket(socket.AF_INET, socket.SOCK_STREAM) 
     self.set_reuse_addr() 
     self.bind((host, port)) 
     self.listen(2) 

    def handle_accept(self): 
     pair = self.accept() 
     if pair is not None: 
      sock, addr = pair 
      print('Incoming connection from %s' % repr(addr)) 
      handler = EchoHandler(sock) 


def main(): 
    host = 'localhost' 
    port = 8081 
    server = EchoServer(host, port) 

    print('Server %s running' % port) 
    asyncore.loop() 


if __name__ == '__main__': 
    main() 

업데이트 : 모든 읽지 않고 서버에 소켓을 닫기 때문에 OSError: [WinError 10038]을 : 당신은 오류가 발생 할
클라이언트의 데이터. 클라이언트 측에서도 마찬가지입니다.
파이썬 문서에서 이들은 very basic 예제라고 명시 적으로 언급합니다.

모든 데이터가 전송되도록하려면 sendall() 메서드를 사용하십시오. 방법 send()은 모든 데이터 전송을 보장하지 않습니다.

당신은이 같은 while 루프 소켓에서 데이터를 읽을해야합니다

my_client.py

import socket 

sock = socket.socket() 
sock.connect(('localhost', 8081)) 
sock.sendall(b'data from client') 

chunk = b'' # socket.recv returns bytes 
data = b'' # defined before to avoid NameError 
while True: 
    chunk = sock.recv(32) 
    if chunk: 
     data += chunk 
    else: 
     break 

print(data) 
sock.close() 

my_server.py

import asyncore 
import socket 
import time 


class EchoHandler(asyncore.dispatcher_with_send): 
    def handle_read(self): 

     chunk = b'' # socket.recv returns bytes 
     data = b'' # defined before to avoid NameError 
     while True: 
      chunk = self.recv(1024) 
      if chunk: 
       data += chunk 
      else: 
       break 

     print('data from client', data) 
     self.sendall(b'data from server') 
     self.close() 


class EchoServer(asyncore.dispatcher): 
    def __init__(self, host, port): 
     asyncore.dispatcher.__init__(self) 
     self.create_socket(socket.AF_INET, socket.SOCK_STREAM) 
     self.set_reuse_addr() 
     self.bind((host, port)) 
     self.listen(2) 

    def handle_accept(self): 
     pair = self.accept() 
     if pair is not None: 
      sock, addr = pair 
      print('Incoming connection from %s' % repr(addr)) 
      handler = EchoHandler(sock) 


def main(): 
    host = 'localhost' 
    port = 8081 
    server = EchoServer(host, port) 

    print('Server %s running' % port) 
    asyncore.loop() 


if __name__ == '__main__': 
    main() 
+0

답변 해 주셔서 감사합니다! 클라이언트의 두 번째 다시 시작한 후 (서버가 실행 중) 예외가 발생합니다 ( : [WinError 10038] – Viktor

+0

@Viktor 다음에 전체 오류 (발생 행 포함)를 입력하십시오. 2 주 후에 답을 얻으실 수 있습니다. 오래된 응답을 자유 시간으로 확인해 주셔서 다행입니다. 'OSError : [WinError 10038] 소켓이 아닌 것에 조작을 시도했습니다. –

관련 문제