UDP Chat in Python Using Socket

Here I will share a very basic UDP chat application in Python using sockets.

It can work in point-to-point or broadcast mode.

For Point-to-Point, enter IP and Port.

For Broadcasting mode set the last byte of IP address to 255. i.e. 192.168.0.255.

Port number is HEX, remove the base 16 to make it decimal.

#!/usr/bin/env python
import socket
import sys, select
 
# Read a line. Using select for non blocking reading of sys.stdin
def getLine():
    i,o,e = select.select([sys.stdin],[],[],0.0001)
    for s in i:
        if s == sys.stdin:
            input = sys.stdin.readline()
            return input
    return False
 
host = raw_input("Please Enter IP: ")
port = int(raw_input("Please Enter PORT: "), 16) # Base 16 for hex value
 
send_address = (host, port) # Set the address to send to
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)    # Create Datagram Socket (UDP)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Make Socket Reusable
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) # Allow incoming broadcasts
s.setblocking(False) # Set socket to non-blocking mode
s.bind(('', port)) #Accept Connections on port
print "Accepting connections on port", hex(port)
 
while 1:
    try:
        message, address = s.recvfrom(8192) # Buffer size is 8192. Change as needed.
        if message:
            print address, "> ", message
    except:
        pass
 
    input = getLine();
    if(input != False):
        s.sendto(input, send_address)

 

2 thoughts on “UDP Chat in Python Using Socket”

  1. HI
    I’m trying your code, but I don’t understand the error that I’m getting. Details below. thanks, David.
    Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:40:30) [MSC v.1500 64 bit (AMD64)] on win32
    Type “copyright”, “credits” or “license()” for more information.
    >>>
    ============== RESTART: C:/Python27/Scripts/codeninjas_chat.py ==============
    Please Enter IP: 192.168.2.255
    Please Enter PORT: 51717
    Accepting connections on port 0xca05

    Traceback (most recent call last):
    File “C:/Python27/Scripts/codeninjas_chat.py”, line 36, in
    input = getLine();
    File “C:/Python27/Scripts/codeninjas_chat.py”, line 10, in getLine
    i,o,e = select.select([sys.stdin],[],[],0.0001)
    UnsupportedOperation: fileno

  2. Hi, still getting errors. I’m using python 3.5.4
    —————————————————————————————
    Traceback (most recent call last):
    File “C:/Users/david000/AppData/Local/Programs/Python/Python35-32/Scripts/udp_code_ninja_chat.py”, line 40, in
    input = getLine();
    File “C:/Users/david000/AppData/Local/Programs/Python/Python35-32/Scripts/udp_code_ninja_chat.py”, line 11, in getLine
    i,o,e = select.select([sys.stdin],[],[],0.0001)
    io.UnsupportedOperation: fileno
    ———————————————————————————————-

Leave a Reply

Your email address will not be published. Required fields are marked *

Exit mobile version