1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
#!/usr/bin/python3 # -*- coding:utf-8 -*- import socket, select, json TOKEN = '1234567' HOST = '127.0.0.1' PORT = 50009 SOCKET_TIMEOUT = 3 # seconds BACKLOG = 10 BUFSIZE = 4096 # See: http://memo.saitodev.com/home/python_network_programing/ def initSocket(): server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) readfds = set([server_sock]) try: server_sock.bind((HOST, PORT)) server_sock.listen(BACKLOG) while True: rready, wready, xready = select.select(readfds, [], []) for sock in rready: if sock is server_sock: # fd = sock.fileno() # print("fd: %d" % fd) sock.settimeout(SOCKET_TIMEOUT) conn, address = server_sock.accept() readfds.add(conn) else: buffer = sock.recv(BUFSIZE) if len(buffer) == 0: sock.close() readfds.remove(sock) else: ret = getSendValue(command(buffer)) sock.send(ret) # sock.close() readfds.remove(sock) except Exception as e: print("Exception: " + str(e)) finally: for sock in readfds: sock.close() server_sock.close() # @param buffer receive buffer data # @return dict def command(buffer): try: data = getReceiveValue(buffer) print("Receive: ", data) if 'token' not in data or data['token'] != TOKEN: msg = "token error." print(msg) return {"message": msg} if 'command' not in data: msg = "Receive message is failed, key 'command' not found." print(msg) return {"message": msg} cmd = data['command'] return {"Receive command": cmd} except Exception as e: return {"exception": str(e)} def getReceiveValue(buffer): return json.JSONDecoder().decode(buffer.decode('utf-8').strip()) def getSendValue(value): if not (isinstance(value, list) or isinstance(value, dict) or isinstance(value, tuple)): value = {value} return bytes(json.JSONEncoder().encode(value), 'utf-8') def main(): print("Backend start") while True: initSocket() print("Escape main loop...") if __name__ == '__main__': main() |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
<?php $sendMessage = array( 'cmd' => 'commandA', ); $result = commBackend($sendMessage); print_r($result); function commBackend($sendMessage) { $sendMessage['token'] = '1234567'; $address = '127.0.0.1'; $service_port = 50009; $timeout_sec = 3; // sec $timeout = time() + $timeout_sec; try { $fp = fsockopen($address, $service_port); if (!$fp) { throw new Exception('Cannot communicate Backend.'); } // non blocking, need to timeout. stream_set_blocking($fp ,0); stream_set_timeout($fp, $timeout_sec); fwrite($fp, json_encode($sendMessage)); $contents = ''; do { if ($timeout - time() <= 0) { $timeout = -1; break; } // echo '.'; $contents .= fread($fp, 8192); } while (!feof($fp)); $info = stream_get_meta_data($fp); // print_r($info); fclose($fp); if ($info['timed_out'] || $timeout === -1) { throw new Exception('Communication with the backend timed out.'); } // echo $contents; $res = json_decode($contents); // json string to object // print_r($res); return $res; } catch (Exception $e) { echo $e->getMessage(); throw new Exception($e->getMessage()); } } |