Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- """Socket HTTP server & client reimplementation
- This is sample script to study how Socket works and
- how HTTP is proceeded.
- """
- from select import select
- import socket
- import sys
- from time import sleep
- ADDR = ('localhost', 8080)
- class HTTPClient(object):
- """HTTP client class
- One thing really important is that there's no EOT in socket.
- If send or recv returns 0, the network is broken.
- A client class has two jobs. One is offering send and recv to
- a server class. Another is just as a client software.
- """
- def __init__(self, s=None):
- if not s:
- self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- else:
- self.s = s
- def connect(self, addr=ADDR):
- self.s.connect(addr)
- def send(self, msg):
- msglen = len(msg)
- sent = 0
- while sent < msglen:
- sent_bytes = self.s.send(msg[sent:])
- if sent_bytes == 0:
- raise RuntimeError('socket connection broken')
- sent += sent_bytes
- def recv(self, byte_size=525, ans=None):
- msg = ''
- while True:
- try:
- buf = self.s.recv(byte_size)
- msg += buf
- if msg == ans:
- print msg
- break
- except (KeyboardInterrupt, SystemExit), e:
- print e
- break
- def close(self):
- self.s.close()
- class HTTPServer(object):
- """HTTP server class
- A server socket only produces client sockets (client_sock) and
- each client socket does send and recieve data.
- A server class needs a client class as well.
- """
- def __init__(self):
- self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- def bind(self, addr=ADDR):
- self.s.bind(addr)
- def listen(self, max_requests=5):
- self.s.listen(max_requests)
- def accept(self):
- while True:
- try:
- (client_sock, addr) = self.s.accept()
- client = HTTPClient(client_sock)
- print 'sending to', addr[0], addr[1]
- client.send('Hello world.')
- print 'closing a client...'
- client.close()
- except (KeyboardInterrupt, SystemExit), e:
- print e
- break
- def close(self):
- self.s.close()
- def run_test_server():
- server = HTTPServer()
- print 'binding...'
- server.bind()
- print 'listening...'
- server.listen()
- print 'accepting...'
- server.accept()
- print 'closing...'
- server.close()
- print 'all done.'
- def run_test_client():
- client = HTTPClient()
- print 'connecting...'
- client.connect()
- print 'recieving...'
- client.recv(2, 'Hello world.')
- print 'closing...'
- client.close()
- if __name__ == '__main__':
- if sys.argv[1] == '-s':
- run_test_server()
- elif sys.argv[1] == '-c':
- run_test_client()
Add Comment
Please, Sign In to add comment