Background: Every language will have an introductory HelloWorld
Content: Read the basic knowledge of network programming, know that the original network programming also has a little practice
Overview: Echo,chat,proxy
There are specialized exercises on the Internet. Whether it's UNIX network programming or any other book, there's a relevant example.
Echo,chat,proxy here to reproduce the implementation of Python, mainly Python is relatively simple, and later will be added to the PHP swoole
Echo:
import os,sys,platformimport BaseHTTPServerfrom SocketServer import ThreadingMixInimport urllib,urllib2import shutilimport reimport timetry: from cStringIO import StringIOexcept ImportError: from StringIO import StringIOclass 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): passif __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,selectdef Broadcast_data (sock,message): For sockets 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 (Connection_list.append) Print "Chat server started on port {}" +str (port) and true:read_sockets,write_sockets,error_sockets = Select. Select (connection_list,[],[]) for sock in Read_sockets:if sock ==server_socket:sockfd,a DDR = 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 ()
The
Chat client is the same
Chat-client:
Import Socket,select,string,sysdef prompt (): Sys.stdout.write ("<you>") 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 SE RVer '; Sys.exit () else:sys.stdout.write (data) prompt () Else: msg = Sys.stdin.readline () S.send (msg) prompt ()
Proxy (as if there was a small error at the time of the code, it is connected to both sides of the server, are received, and then each in the forward, to go back and forth, write dizzy)
Import Sysimport socketimport threadingdef 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 "% (Localho S_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 (r Emote_buffer) remote_socket.send (local_buffer) print ("[==>] Sent to remote") Remote_buffer = recei Ve_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 (clien T_socket) If Len (remote_buffer): Print ("[==>] Received%d bites from Local_host"%len (Local_ Buffer) Hexdump (local_buffer) Local_buffer = request_handler (local_buffer) r Emote_socket.send (local_buffer) print ("[==>] Sent to remote") Remote_buffer = Receive_from (re Mote_socket) If Len (remote_buffer): Print ("[<==] Received%d bytes from remote."% Len (Remot E_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 ") breakdef hexdump (src,length = +): result =[] digits = 4 if isinstance (Str,uni Code) Else 2 for I in Xrange (0,len (src), length): s = src[i:i+length] Hexa = B '. Join (["%0*x"% (digits,or D (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 bufferdef request_handler (buffer): return bufferdef Response_handl ER (buffer): return Bufferdef Main (): If Len (sys.argv[1:])!=5:print ("Usage:python proxy.py [localhos_host] [l Ocal_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 ()
Getting Started with Linux network programming three-step walk