Tuesday 30 June 2015

Socket based chat application using UDP.

python




In last post on socket based application TCP protocol is used. This section describes how to create a socket for message exchange using User Datagram Protocol a simple connectionless transmission model with a minimum of protocol mechanism. The main advantage of using UDP is that no connection instance is required to build up for client as it requires in case of TCP. Socket itself received data from client with recvfrom function which returns data and address of the client. Server only waits for the client message and no connection request is required, it only receives and sends data without even identifying client individually.

udpServer.py


import socket  # Socket library 

def Main():    # main function

   host = "127.0.0.1"                           # host loop back address to test in 

                                                           # adapter-less machine.
   port = 5001                                    # port for server




  # socket object.
  s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
  s.bind((host,port))                            # binding to host ip and port
 
  print "Server Started.."
  while True:                                      # infinite loop, server always waits for data
    data, addr = s.recvfrom(1024)    # Receiving data from client.
    print "message from: " + str(addr)   
    print "from connected user: " + str(data)
    data = str(data).upper()              # Converting data to upper case
    print "sending: " + str(data)        

    s.sendto(data,addr)                     # sending data back to client
  s.close();                                        # Socket closed when loop terminates.

if __name__ == '__main__':             # Main module invoked.
  Main()


udpClient.py

import socket  # Socket library 

def Main():    # main function

   host = "127.0.0.1"  # host loop back address to test in adapter-less machine.

   port = 5001            # port for server


   server = ('127.0.0.1',5000)


# socket object.
   s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 
   s.bind((host,port))

   message = raw_input('->')                               
# Waits for user input      
   while message != 'q':
      s.sendto(message,server)                              # User input data send to server
      data, addr = s.recvfrom(1024)                     # data received from server
      print "Received from server: " + str(data);
      message = raw_input('->')                           # Waits for user input
   s.close()

if __name__ == '__main__':                 
# Main module invoked.  
  Main()

#python #pythoprogramming #pythoscript #socketprograming

No comments: