Python Socket communication sample / simple data throwing tool

Socket communication sample

Python Socket communication sample. The data transmission itself can be written in a minimum of two lines.

with socket.socket(socket.AF_INET, args.p) as nsocket:
	#Connect only for TCP
	if args.p is socket.SOCK_STREAM:
		nsocket.connect((host, port))
	#Data transmission
	nsocket.send(data)

Simple data throwing tool

An nc command-like, simple data throwing tool with parameters added. Scheduled to be expanded.

import argparse
import socket

#Parameter processing
parser = argparse.ArgumentParser()
parser.add_argument("-p", default=socket.SOCK_STREAM, help="Potocol TCP or UDP")
parser.add_argument("host", help="Hostname or IP Address")
parser.add_argument("port", help="Port number")
parser.add_argument("-m", default='0123456789abcdef' , help="Send data")
parser.add_argument("-f", type=argparse.FileType('rb'), help="Send data from a file")
args = parser.parse_args()

send_data = '0123456789abcdef'
if args.m:
	send_data = args.m.encode()

if args.f:
	send_data = args.f.read()

#Actual communication
with socket.socket(socket.AF_INET, args.p) as nsocket:
	#Connect only for TCP
	if args.p is socket.SOCK_STREAM:
		nsocket.connect((args.host, int(args.port)))
	#Data transmission
	nsocket.send(send_data)
"""
	#Receive response
	nsocket.settimeout(3)
	data = nsocket.recv(1024)
	
	print(repr(data))
"""

Recommended Posts

Python Socket communication sample / simple data throwing tool
Socket communication with Python
Python --Simple multi-thread sample
Send data from Python to Processing via socket communication
Sample data created with python
Socket communication with Python LEGO Mindstorms
Python3 socket module and socket communication flow
Socket communication and multi-thread processing by Python
Python visualization tool for data analysis work
Socket communication by C language and Python
Simple sales tool creation with Python GUI: Quote creation
Data analysis python
Python closure sample
[python] Read data
[Python] [Word] [python-docx] Simple analysis of diff data using python