Python/Sockets

From Omnia
Revision as of 19:12, 1 November 2016 by Kenneth (talk | contribs) (Created page with "== Sockets == Python Sockets - http://docs.python.org/library/socket.html <pre> # Echo server program import socket HOST = '' # Symbolic name meaning all av...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to 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()