How to send socket data based on keyboard input in terminal while receiving incoming UDP data? Data will be send through socket after enter
key is pressed included LF (line feed character).
I only have this minimal UDP server:
import socket
SERV_IPV4, SERV_PORT = ("192.168.43.150", 7777)
udpSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udpSock.bind((SERV_IPV4,SERV_PORT))
while 1:
dataRecv, CLNT_ADDR = udpSock.recvfrom(1024)
print(dataRecv, CLNT_ADDR)
What I expect about program is moreless like how netcat command work: nc -ulp 7777
CodePudding user response:
Use Threading
import socket, threading
SERV_IPV4, SERV_PORT = ("192.168.43.150", 7777)
udpSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udpSock.bind((SERV_IPV4,SERV_PORT))
def receiveData():
while (1):
dataRecv, CLNT_ADDR = udpSock.recvfrom(1024)
print(dataRecv, CLNT_ADDR)
thread = threading.Thread(target=receiveData)
# Get input and send data
thread.join(0)
CodePudding user response:
You can set your socket in non-blocking mode:
import socket
SERV_IPV4, SERV_PORT = ("192.168.43.150", 7777)
udpSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udpSock.bind((SERV_IPV4,SERV_PORT))
udpSock.setblocking(False)
while 1:
try:
dataRecv, CLNT_ADDR = udpSock.recvfrom(1024)
print(dataRecv, CLNT_ADDR)
except socket.error:
# No input from the socket