필자는 공개 서버에 정보를 보내고 (키 교환 방식의 작동 방식을 보여주기 위해) 그것을 특정 클라이언트로 보냅니다. 단 두 명의 고객이 있습니다.파이썬 3.x에서 클라이언트 (1)에서 서버 (2) 클라이언트 (2)
클라이언트 (1)에서 서버로 정보를 가져 오는 방법에 대한 올바른 방향으로 밀어 넣기를 원하면 서버가 해당 정보를 클라이언트 (2)로 리디렉션하게하십시오. 나는 정보를 서버에서 보내고받는 방법에 익숙해지면서 코드를 다소 엉망으로 만들었지 만, 클라이언트를 차별화하고 특정 클라이언트에게 정보를 보내는 방법을 모르겠습니다. (현재 2 시간 정도의 연구 결과) 현재 서버 거의 변경되지 않은 python3 docs의 코드 (:
import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
"""
The RequestHandler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print("{} wrote:".format(self.client_address[0]))
print(self.data)
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
# Create the server, binding to localhost on port 9999
server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
내 클라이언트 거의 변경되지 않은 python3 docs의 코드 (:
import socket
import time
data = "matt is ok"
def contactserver(data):
HOST, PORT = "localhost", 9999
# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to server and send data
sock.connect((HOST, PORT))
sock.sendall(bytes(data, "utf-8"))
# Receive data from the server and shut down
received = str(sock.recv(1024), "utf-8")
print("Sent: {}".format(data))
print("Received: {}".format(received))
return format(received)
while True:
k = contactserver('banana')
time.sleep(1)
print(k)
그리고? 문서에서 변경되지 않은 코드를 붙여 넣는 작업을 수행했습니다. 해당 코드에 대한 질문이 있으십니까? – abarnert
@abarnert 클라이언트 (1)에서 서버로 정보를 가져 오는 방법에 대한 올바른 방향으로 밀어 넣기를 바라고, 그런 다음 서버가 해당 정보를 클라이언트 (2)로 리디렉션하도록합니다. 코드를 다소 복잡하게 만들었지 만 서버에서 정보를 보내고받는 방법에 익숙해졌지만 클라이언트를 차별화하고 특정 클라이언트에게 정보를 보내는 방법을 알지 못했습니다. – user2719977
'socketserver'는 실제로 그런 식으로 사용하기위한 것이 아닙니다. 배우기 쉽고, 소스를 만드는 것이 쉽지 않습니다 (http://hg.python.org/cpython/file/3.3 /Lib/socketserver.py)보다 복잡한 프로젝트의 샘플 코드로 이해하기 쉽습니다. 클라이언트 간 통신에 도움이되는 프레임 워크가 있지만 '소켓 서버'는 그 중 하나가 아닙니다. 즉, 내가 대답에서 설명했듯이, 당신이 원하는 것은 ~ 할 수 있습니다 ...하지만 훨씬 더 복잡해지기를 원한다면 아마도 '소켓 서버'를 넘어서고 싶을 것입니다. – abarnert