Python調用遠程Socket介面

來源:互聯網
上載者:User

Web應用通訊通常都喜歡用HTTP介面,但不排除直接socket通訊的情況。

socket除了server端構建麻煩些(需要考慮很多實際情況),對於調用者來說構建個client端其實不比http麻煩多少。

#!/usr/bin/env python# -*- coding:utf-8 -*-# Auther: linvoimport socketclass Client(object):    """    調用遠程Socket介面    <code>    try:        obj = Client(host, port)        ret = obj.send(data)    except Exception, e:        ret = e    </code>    """    def __init__(self, host, port, timeout = 5):        """        連結遠程介面服務        """        self.sock = None        try:            socket.setdefaulttimeout(timeout)             self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)             self.sock.connect((host, port))        except socket.error, e:            raise Exception('SOCKET ERROR:' + str(e))        except Exception, e:            raise Exception('CONNECT ERROR:' + str(e))    def send(self, data):        """        socket通訊        發送和接收        data: 發送的資料        ret: 接收的資料        """        ret = None        # 連結成功,開始傳輸        if self.sock:            data = str(data)            try:                result = self.sock.sendall(data)            except Exception, e:                result = str(e)            if result is not None:                raise Exception('SEND ERROR:' + str(result))            else:                # 接收                 ret = ''                try:                    while True:                        buffer = self.sock.recv(2048)                        if buffer:                             ret += buffer                        else:                            break                except Exception, e:                    raise Exception('RECV ERROR:' + str(e))        return ret

順便給個簡易的server端,以便測試:

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()
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.