Friday, June 22, 2012

Using IP sockets in jython


Using IP sockets

IP sockets are used to initiate an IP communication between two processes on the network. Jython greatly simplifies the creation of IP servers (waiting for IP packets) or IP clients (sending IP packets).
The following example shows the implementation of a very basic IP server. It waits for data coming from client software, and writes each received packet into the file c:/temp/socketserver.log. If a server receives the packet STOPSERVER, the server stops:

Server

import socket
import time
HOST = ''
PORT = 9191 # Arbitrary port (not recommended)
LOG_FILE = 'c:/temp/sockserver.log'
mySock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
mySock.bind((HOST, PORT))
logfile = open(LOG_FILE, 'w')
try:
  print >> logfile, '*** Server started : %s' % time.strftime('%Y-%m-%d %H:%M:%S')
  while 1:
    data, addr = mySock.recvfrom(1024)
    print >> logfile, '%s (%s): %s' % (time.strftime('%Y-%m-%d %H:%M:%S'), addr, data)
    if data == 'STOPSERVER':
      print >> logfile, '*** Server shutdown at %s by %s' % (time.strftime('%Y-%m-%d %H:%M:%S'), addr)
      break
finally:
  logfile.close()

Client

The following example can be used ot test the above server. It sends two packets before asking the server to stop.
import socket
import sys
PORT = 9191 # Same port as the server
HOST = 'SERVER_IP_ADDRESS'
mySock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
mySock.sendto('Hello World !', (HOST, PORT))
mySock.sendto('Do U hear me?', (HOST, PORT))
mySock.sendto('STOPSERVER', (HOST, PORT))


No comments:

Post a Comment