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()
무슨 에러가 발생합니까? –
오류 및 예외는 없지만 handle_accept() 함수는 두 번째 클라이언트 연결 시도에서만 실행됩니다. – Viktor
필자는 문서에서 벗어나서'asyncore'에 익숙하지 않았지만'handle_except'에서'accept'를 호출해서는 안된다고 생각합니다. 서버는 연결을 수락 한 후 해당 함수를 호출 할 수 있으므로 중복 될 수 있습니다. –