[PYTHON] Start communication with UDP and send and receive with TCP

I wrote it as a trial, but I didn't seem to use it, so a memo for some time

UDPServer_and_TCPClient.py

#Run UDP server and TCP client
from socket import socket, AF_INET, SOCK_DGRAM, SOCK_STREAM

#A function that starts a connection with TCP and sends data
def tcp_send():
	with socket(AF_INET, SOCK_STREAM) as s:
		s.connect(('127.0.0.1', 50010))
		while True:
			s.sendall(b'hello')

#UDP server
udp_server = socket(AF_INET, SOCK_DGRAM)
udp_server.bind(('', 8888))

while True:
	msg, address = udp_server.recvfrom(8192)
	if msg.decode('utf-8') == "tcp_start":
		#When you receive a specific string, connect the TCP client and send
		tcp_send()
		break

udp_server.close()

TCPServer_and_UDPClient.py

#Run TCP server and UDP client
from socket import socket, AF_INET, SOCK_DGRAM, SOCK_STREAM

#Function to send UDP
def udp_send(): 
	udp_client = socket(AF_INET, SOCK_DGRAM)
	udp_client.sendto("tcp_start".encode(), ("127.0.0.1", 8888))

#Create TCP server
with socket(AF_INET, SOCK_STREAM) as tcp_server:
	tcp_server.bind(('127.0.0.1', 50010))
	tcp_server.listen(1)
	
	#UDP transmission
	udp_send()
	while True:
		conn, addr = tcp_server.accept()
		with conn:
			while True:
				data = conn.recv(1024)
				print(data.decode('utf-8'))

Recommended Posts

Start communication with UDP and send and receive with TCP
Send and receive binary data via serial communication with python3 (on mac)
Send and receive Flask images
Send and receive data with MQTT via Watson IoT Platform
[aws] Send and receive sqs messages
Login with PycURL and receive response
POST variously with Python and receive with Flask
Send and receive image data as JSON over the network with Python
Communication and networking
Start numerical calculation in Python (with Homebrew and pip)
POST the image with json and receive it with flask