Python/Sockets

From Omnia
Jump to: navigation, search

Sockets

Python Sockets - http://docs.python.org/library/socket.html

# Echo server program
import socket

HOST = ''                 # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
    data = conn.recv(1024)
    if not data: break
    conn.send(data)
conn.close()
# Echo client program
import socket

HOST = 'daring.cwi.nl'    # The remote host
PORT = 50007              # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)

See also: Socket Programming HOWTO — Python v2.7.1 documentation - http://docs.python.org/howto/sockets.html

Telnet Example

# code in progress

# simple telnet server

import socket, sys

HOST = ''
PORT = 23
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
print "Waiting..."
conn, addr = s.accept()
print "Connected."
print 'Connected by', addr
conn.send("Hello\r\n")
clean_data = ''
quit = False
while not quit:
  data = conn.recv(1024)
  if not data: break
  for c in data:
    # clean data
    if c in ' abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ':
        clean_data += c
    # process new line
    if c in '\n':
        clean_data = clean_data.strip()
        print clean_data
        if clean_data == "quit":
            quit = True
            clean_data = ""
            conn.send("Now go away\r\n")
            break
        clean_data = ""
  #sys.stdout.write("data: " + data + "\n")
  #if '\n' in data or '\r' in data:
  #  conn.send('\r\n')
  #else:
  #  conn.send(data)
print "Connection closed."
conn.close()