Socket communication using socketserver with python now

Purpose

With reference to the following, it is a memorandum when TCP / UDP socket communication with python, although it feels more like now.

socketserver --- Network server framework

About socket communication

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

TCP socket communication

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

UDP socket communication

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.

Remarks

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

Socket communication

reference

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

Socket communication using socketserver with python now
Socket communication with Python
Socket communication with Python LEGO Mindstorms
Serial communication with Python
Serial communication with python
WiringPi-SPI communication using Python
HTTP communication with Python
TCP communication using Socket module-Python3
Using Quaternion with Python ~ numpy-quaternion ~
[Python] Using OpenCV with Python (Basic)
View Python communication with Fiddler
Using OpenCV with Python @Mac
Send using Python with Gmail
Serial communication control with python and I2C communication (using USBGPIO8 device)
Serial communication control with python and SPI communication (using USBGPIO8 device)
Complement python with emacs using company-jedi
Harmonic mean with Python Harmonic mean (using SciPy)
Using Rstan from Python with PypeR
[Python] Using OpenCV with Python (Image transformation)
[Python] Using OpenCV with Python (Edge Detection)
Python3 socket module and socket communication flow
Notes on using rstrip with python.
I tried SMTP communication with Python
When using MeCab with virtualenv python
Precautions when using six with Python 2.5
[AWS] Using ini files with Lambda [Python]
Socket communication and multi-thread processing by Python
Try mathematical formulas using Σ with python
Behind the flyer: Using Docker with Python
Using Python and MeCab with Azure Databricks
[Python] [Windows] Serial communication in Python using DLL
Try using Python with Google Cloud Functions
Check stock prices with slackbot using python
Working with OpenStack using the Python SDK
Tips for using python + caffe with TSUBAME
Socket communication by C language and Python
I'm using tox and Python 3.3 with Travis-CI
[Personal memo] julia --Using Python library with julia using PyCall
FizzBuzz with Python3
Scraping with Python
Scraping with Python
Python with Go
Twilio with Python
Integrate with Python
Debug with VS Code using boost python numpy
Start using Python
Now Python3 (Other)
Play with 2016-Python
I tried using mecab with python2.7, ruby2.3, php7
AES256 with python
Tested with Python
python starts with ()
with syntax (Python)
Recent ranking creation using Qiita API with Python
Bingo with python
Zundokokiyoshi with python
Python Socket communication sample / simple data throwing tool
Scraping using Python
Excel with Python
Microcomputer with Python
What are you using when testing with Python?