背景:每一个语言都会有入门的helloworld
内容:看完网络编程的基础知识,知道原来网络编程也有小练习
概述:Echo,Chat,Proxy

网上有专门的练习。不管是UNIX网络编程还是其他的书籍都会有相关的举例

Echo,chat,Proxy在这里统一再现Python的实现,主要是Python的比较简单,稍后也会补充一下PHP的swoole

Echo:

import os,sys,platform
import BaseHTTPServer
from SocketServer import ThreadingMixIn
import urllib,urllib2
import shutil
import re
import time
try:
 from cStringIO import StringIO
except ImportError:
 from StringIO import StringIO

class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
 def do_GET(self):
  f = StringIO()
  f.write(self.path)
  length = f.tell()
  f.seek(0)
  self.response(length)
  if f:
    shutil.copyfileobj(f,self.wfile)
    f.close()
 def response(self,length):
    self.send_response(200)
    self.send_header("Content-type","text/html")
    self.send_header("Content-Length",str(length))
    self.end_headers()

class ThreadingServer(ThreadingMixIn,BaseHTTPServer.HTTPServer):
    pass
if __name__ =="__main__":
    serveraddr = ("",int(sys.argv[1]))
    print "LISTEN Port(%s)" % (int(sys.argv[1]))
    srvr = ThreadingServer(serveraddr,SimpleHTTPRequestHandler)
    srvr.serve_forever()

Chat:

import socket,select

def broadcast_data(sock,message):
    for socket in CONNECTION_LIST:
        if socket != server_socket and socket !=sock:
            try:
                socket.send(message)
            except:
                socket.close()
                CONNECTION_LIST.remove(socket)

if __name__ =='__main__':

    CONNECTION_LIST = []
    RECV_BUFFER = 4096
    HOST = '0.0.0.0'
    PORT = 3446

    server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
    server_socket.bind((HOST,PORT))
    server_socket.listen(10)

    CONNECTION_LIST.append(server_socket)

    print "Chat server started on port {}"+str(PORT)

    while True:
        read_sockets,write_sockets,error_sockets = select.select(CONNECTION_LIST,[],[])

        for sock in read_sockets:
            if sock ==server_socket:
                sockfd,addr = server_socket.accept()
                CONNECTION_LIST.append(sockfd)
                print ("Client (%s,%s) connected" % addr)

                broadcast_data(sockfd,"[%s:%s] entered room\n"% addr)
            else:
                try:
                    data = sock.recv(RECV_BUFFER)
                    if data:
                        broadcast_data(sock,"\r"+'<'+str(sock.getpeername())+'>'+data)
                except:
                    broadcast_data(sock,"Client (%s,%s) is offline"% addr)
                    print ("Client (%s,%s) is offline"% addr)
                    sock.close()
                    CONNECTION_LIST.remove(sock)
                    continue
    server_socket.close()

聊天的客户端也是一样的
Chat-Client:

import socket,select,string,sys

def prompt():
    sys.stdout.write(" ")
    sys.stdout.flush()

if __name__=="__main__":
    if(len(sys.argv)<3):
        print "Usage: python chat_client.py host port"
        sys.exit()

    host = sys.argv[1]
    port = int(sys.argv[2])

    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.settimeout(2)

    try:
        s.connect((host,port))
    except:
        print ("Unable to connnect")
        sys.exit()
    print("Connected to remote host,Start send message")
    prompt()

    while True:
        rlist = [sys.stdin,s]

        read_list,write_list,error_list = select.select(rlist,[],[])

        for sock in read_list:
            if sock ==s:
                data = sock.recv(4096)
                if not data:
                    print '\nDisconnected from chat server';
                    sys.exit()
                else:
                    sys.stdout.write(data)
                    prompt()
            else:
                msg = sys.stdin.readline()
                s.send(msg)
                prompt()

Proxy(好像当时码的时候有小错误,反正就是连接两边的服务器,都接收过来,然后各自在转发出去,来来回回,写晕了)

import sys
import socket
import threading

def server_loop(local_host,local_port,remote_host,remote_port,receive_first):
    server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    try:
        server.bind(local_host,local_port)
    except:
        print ("[!!] Failed to listen on %s:%d"% (local_host,local_port))
        print ("[!!] Check for other listening sockets or correct permissions")
        sys.exit(0)
    print ("[*] Listening on $s:%d"% (localhos_host,local_port))
    server.listen(5)
    while True:
        client_socket.addr = server.accept()
        print ("[==>] Received incoming connnection from %s:%d"% addr[0],addr[1])
        proxy_thread = threading.Thread(target = proxy_handler,args =(client_socket,remote_host,remote_port,receive_first))
        proxy_thread.start()

def proxy_handler(client_socket,remote_host,remote_port,receive_first):
    remote_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    remote_socket.connect((remote_host,remote_port))
    if receive_first:
        remote_buffer = receive_from(remote_socket)
        hexdump(remote_buffer)
        remote_buffer = response_handler(remote_buffer)
        remote_socket.send(local_buffer)
        print("[==>] Sent to remote")
        remote_buffer = receive_from(remote_socket)
        if len(remote_buffer):
            print("[<==] Sending %d bytes to local_host."%len(remote_buffer))
            client.send(remote_buffer)
        while True:
            local_buffer = receive_from(client_socket)
            if len(remote_buffer):
                print ("[==>] Received %d bites from local_host" %len(local_buffer))
                hexdump(local_buffer)
                local_buffer = request_handler(local_buffer)
                remote_socket.send(local_buffer)
                print("[==>] Sent to remote")
            remote_buffer = receive_from(remote_socket)
            if len(remote_buffer):
                print("[<== ] Received %d bytes from remote." % len(remote_buffer))
                hexdump(remote_buffer)    
                remote_buffer = response_handler(remote_buffer)
                client.socket.send(remote_buffer)
                print("[<==] Sent to Sent to local_host")
            if not len(local_buffer) or not len(remote_buffer):
                client_socket.close()
                remote_socket.close()
                print("[*] No more data.Closing connections") 

                break

def hexdump(src,length = 16):
    result =[]
    digits = 4 if isinstance(str,unicode) else 2
    for i in xrange(0,len(src),length):
        s = src[i:i+length] 
        hexa = b' '.join(["%0*x"%(digits,ord(x)) for x in s])
        text = b''.join([x if 0x20 <= ord(0) <=0x7F else b'.' for x in s])
        result.append(b'%04X %-*s %s'%(i,length*(digits + 1),hexa,text))
    print(b'\n'.join(result))

def receive_from(connection):
    buffer = ''
    connection.settimeout(2)
    try:
        while True:
            data = connection.recv(4096)
            if not data:
                break
            buffer +=data
    except:
        pass
    return buffer

def request_handler(buffer):
    return buffer

def response_handler(buffer):
    return buffer

def main():
    if len(sys.argv[1:])!=5:
        print("Usage:python proxy.py [localhos_host] [local_port] [remote_host] [remote_port] [receice_first]")
        print("Example:python proxy.py 127.0.0.1")
        sys.exit(0)

    local_host = sys.argv[1]
    local_port = int(sys.argv[2])

    remote_host = sys.argv[3]
    remote_port = sys.argv[4]

    receive_first = sys.argv[5]
    if 'True' in receive_first:
        receive_first = True
    else:
        receive_first = False    
    server_loop(local_host,local_port,remote_host,remote_port,receive_first)
main()