返回顶部

收藏

socket Service-Client

更多
#!/usr/bin/env python
# coding: utf-8
#
# author: Tim Wang
# date: 2015-05-21
# filename: common_lib/net/sockettools.py

import socket
import sys
from thread import start_new_thread
import cPickle as pickle

def mksocket():
    try:
        return socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    except socket.error, msg:
        print 'Failed to create socket. Error code: %s ,' % msg[0]
        print 'Error message : %s' % msg[1]
        sys.exit(1)

def clientthread(conn, func):
    while True:
        data = conn.recv(1024)
        if not data or not data.strip():
            break
        conn.sendall(func(eval(data)))
    print "Peer:", conn.getpeername(),
    conn.close()
    print "disconnect."

def pkl(func):
    def _wrap(argkwg):
        args, kwgs = argkwg
        result = func(*args, **kwgs)
        return pickle.dumps(result)
    return _wrap

class SocketService(object):

    def __init__(self, addr, listen=10, func=None):
        self.addr = addr
        self.sock = mksocket()
        self.func = None
        try:
            self.sock.bind(self.addr)
        except socket.error, msg:
            print 'bind failed. error: [%d] %s' % (msg[0], msg[1])
            sys.exit(2)
        self.sock.listen(listen)
        self.register(func)

    def register(self, fn):
        default = lambda x: 'OK...' + x
        self.func = fn or default

    def sloop(self, func=None):
        if func:
            self.register(func)
        while 1:
            conn, addr = self.sock.accept()
            print addr, "connected."
            start_new_thread(clientthread, (conn, self.func))
        self.sock.close()

class SocketAgent(object):

    def __init__(self, addr):
        self.addr = addr
        self.sock = mksocket()
        self.sock.connect(self.addr)

    def __call__(self, *args, **kwgs):
        self.sock.sendall(repr((args, kwgs)))
        return pickle.loads(self.sock.recv(4096))

    def __del__(self):
        self.sock.close()

标签:python

收藏

0人收藏

支持

0

反对

0

发表评论