Web Application Communication generally uses HTTP interfaces, but direct socket communication is not ruled out.
In addition to server-side construction, socket is a little more troublesome (many actual situations need to be considered). It is no more troublesome for callers to build a client than HTTP.
#! /Usr/bin/ENV Python #-*-coding: UTF-8-*-# auther: linvoimport socketclass client (object): "Call remote socket interface <code> try: OBJ = client (host, Port) ret = obj. send (data) failed t exception, E: ret = e </code> "" def _ init _ (self, host, port, timeout = 5 ): "link remote interface service" "self. sock = none try: socket. setdefatimetimeout (timeout) self. sock = socket. socket (socket. af_inet, socket. sock_stream) self. sock. connect (host, Port) failed t socket. error, E: Raise exception ('socket error: '+ STR (E) Except t exception, E: Raise exception ('connect error:' + STR (e )) def send (self, data): "socket communication sends and receives data: sent data RET: Received data" "ret = none # connection successful, start transmitting if self. sock: Data = STR (data) Try: Result = self. sock. sendall (data) failed t exception, E: Result = STR (e) If result is not none: Raise exception ('send error: '+ STR (result) else: # receive ret = ''try: While true: Buffer = self. sock. recv (2048) If Buffer: Ret + = buffer else: Break failed t exception, E: Raise exception ('recv error: '+ STR (E) return ret
By the way, a simple server is provided for testing:
import socketsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.bind(('localhost', 9801))sock.listen(5)while True: connection, address = sock.accept() try: connection.settimeout(5) buf = connection.recv(2048) connection.send(buf) except socket.timeout: print 'time out' connection.close()