Reputation: 343
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
Upvotes: 0
Views: 334
Reputation:
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))
dataRecv = ""
CLNT_ADDR = None
def receiveData():
global CLNT_ADDR
global dataRecv
while (1):
dataRecv, CLNT_ADDR = udpSock.recvfrom(1024)
print(dataRecv, CLNT_ADDR)
recvThread = threading.Thread(target=receiveData)
recvThread.start()
recvThread.join(0)
while (1):
dataSend = (input() + "\n").encode()
print(dataSend)
udpSock.sendto(dataSend,CLNT_ADDR)
Upvotes: 1
Reputation: 71
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
Upvotes: 1