With reference to the following, it is a memorandum when TCP / UDP socket communication with python, although it feels more like now.
Socket The Internet uses a communication protocol called TCP / IP, but in order to use that TCP / IP programmatically, a special doorway connecting the world of programs and the world of TCP / IP is required. The gateway is the socket, which is a major feature of TCP / IP programming. Source: http://research.nii.ac.jp/~ichiro/syspro98/socket.html
The alphabet sent by the client side to the server side is capitalized by the server side and returned to the client.
receiver.py
import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
self.data = self.request.recv(1024).strip()
print("{} wrote:".format(self.client_address[0]))
print(self.data)
self.request.sendall(self.data.upper())
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server:
server.serve_forever()
sender.py
import socket
import sys
HOST, PORT = "localhost", 9999
data = " ".join(sys.argv[1:])
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect((HOST, PORT))
sock.sendall(bytes(data + "\n", "utf-8"))
received = str(sock.recv(1024), "utf-8")
print("Sent: {}".format(data))
print("Received: {}".format(received))
Execute
$ python receive.py
$ python sender.py "hello world"
Sent: hello world
Received: HELLO WORLD
Unlike TCP, UDP has no connection and keeps sending data.
receiver.py
import socketserver
class MyUDPHandler(socketserver.BaseRequestHandler):
def handle(self):
data = self.request[0].strip()
socket = self.request[1]
print("{} wrote:".format(self.client_address[0]))
print(data)
socket.sendto(data.upper(), self.client_address)
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
with socketserver.UDPServer((HOST, PORT), MyUDPHandler) as server:
server.serve_forever()
sender.py
import socketserver
class MyUDPHandler(socketserver.BaseRequestHandler):
def handle(self):
data = self.request[0].strip()
socket = self.request[1]
print("{} wrote:".format(self.client_address[0]))
print(data)
socket.sendto(data.upper(), self.client_address)
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
with socketserver.UDPServer((HOST, PORT), MyUDPHandler) as server:
server.serve_forever()
Execute
$ python receive_udp.py
$ python sender_udp.py "hello world. udp."
Sent: hello world. udp.
Received: HELLO WORLD. UDP.
If the communication data is large, there will be a difference in execution time and handling of missing data, but it is omitted because it is a trial. Learn more about how UDP differs from TCP
socketserver --- Network server framework Communication processing by Python cpython/Lib/socketserver.py Let's learn the basics of socket communication that I knew Matsumoto Naoden Programming Okite 16th Network Programming (Socket Edition) Socket communication
Recommended Posts