# Sockets in python

Execution
server# cat pyserver 
#!/usr/bin/python

import socket
import sys

HOST = 'localhost'
PORT = 1024

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

server_socket = (HOST, PORT)
server.bind(server_socket)
print 'Starting up on %s port %s' % server_socket

server.listen(5)

while True:
 try:
  connection, client_socket = server.accept()
  print 'Connection from', client_socket

  data = connection.recv(4096)

  if data:
   print 'Received', data
   data = data.strip()
   connection.send('%s\n%s ack\n%s' % ('-'*15, data, '-'*15))

  connection.shutdown(socket.SHUT_RD | socket.SHUT_WR)

 except KeyboardInterrupt, e: # CTRL+C
  print ''
  break

connection.close()
print 'Connection closed'

server.close()

server# ./pyserver
client# cat client 
#!/usr/bin/python

import socket
import sys

HOST = 'localhost'
PORT = 1024

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server_socket = (HOST, PORT)
client.connect(server_socket)

client.send(sys.argv[1])
data = client.recv(1024)

client.close()

print 'Received:'
print data

client# ./pyclient

No comments: