Python calls the remote socket interface

Source: Internet
Author: User
Tags socket error

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()
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.