Using UDP, is it possible to have client-to-client communication? I am using the python socket library in the code below. I can send messages over the UDP sockets I create, but I cannot receive messages that are sent to the IP address I have established for a given client.
The process is to:
- Run the python script below in two different terminal windows and observe the messages sent between the sockets
- I can receive the messages only when I bind to a local host using socket.bind(), but I cannot bind to an external IP address (necessary for facilitating client-to-client information). As a result, I am using socket.connect().
Does anyone have any tips for how I can connect to other clients using external IP addresses and send messages across the UDP sockets?
import socket
import threading
import os
s = socket.socket(socket.AF_INET , socket.SOCK_DGRAM )
s.connect(("198.168.225.242", 2222))
print("\t\t\t====> UDP CHAT APP <=====")
print("==============================================")
nm = input("ENTER YOUR NAME : ")
print("\nType 'quit' to exit.")
ip,port = input("Enter IP address and Port number that you want to send messages to: ").split()
def send():
while True:
ms = input(">> ")
if ms == "quit":
os._exit(1)
sm = "{} : {}".format(nm,ms)
s.connect((str(ip), int(port)))
s.sendto(sm.encode() , (ip,int(port)))
def rec():
while True:
s.connect_ex((str(ip), int(port)))
msg = s.recvfrom(1024)
print("\t\t\t\t >> " + msg[0].decode() )
print(">> ")
x1 = threading.Thread( target = send )
x2 = threading.Thread( target = rec )
x1.start()
x2.start()