Python之可读写的socket逻辑

## 说明

      该脚本支持对套接字进行读写操作(而非简单的阻塞式应答服务)

      用于充当服务器角色,向其发起心跳、根据需要返回指定的数据模拟等....


## 源码 ( s_ok.py )

import threading
import socket
import time

encoding = 'utf-8'
BUFSIZE = 1024
gCount = 0

class Writer(threading.Thread):
    def __init__(self, client):
        threading.Thread.__init__(self)
        self.client = client
        self.count = 0
    def run(self):
        while True:
            data = self.readline()
            if(data):
                ret = bytes.decode(data, encoding)
                print "=> Client: %s" % (ret)
                self.client.send(ret)
            else:
                break
        print "close:", self.client.getpeername()
    def readline(self):
        rec = raw_input("Input Msg:")
        if rec:
            string = rec
        else:
            string = "blank"
        return string

# a read thread, read data from remote
class Reader(threading.Thread):
    def __init__(self, client):
        threading.Thread.__init__(self)
        self.client = client
        self.count = 0
    def run(self):
    	#Writer(self.client).start()
    	self.client.send("Welecom CMIP Service....")
        while True:
            data = self.client.recv(BUFSIZE)
            if(data):
                string = bytes.decode(data, encoding)
                self.count = self.count + 1
                print "from client::(%d)-->%s\n\n" % (self.count,string)
                #time.sleep(2)
                #p1,p2 = string.split("&")
                #p11,p12 = p1.split("=")
                #print p12
                #p21,p22 = p2.split("=")
                #print p22
                ret = """
                		  0 
                		  1231231 
                		  0  
                		 
                		 	 fails 
                		 	 404  
                		 	 2  
                		 	 70 
                		 	 CMD 
                		 
                		 
                	"""
                self.client.send(ret)
            else:
                break
        print "close:", self.client.getpeername()
        
    def readline(self):
        rec = self.inputs.readline()
        if rec:
            string = bytes.decode(rec, encoding)
            if len(string)>2:
                string = string[0:-2]
            else:
                string = ' '
        else:
            string = False
        return string

# a listen thread, listen remote connect
# when a remote machine request to connect, it will create a read thread to handle
class Listener(threading.Thread):
    def __init__(self, port):
        threading.Thread.__init__(self)
        self.port = port
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind(("0.0.0.0", port))
        self.sock.listen(0)
    def run(self):
        print "listener started"
        while True:
            client, cltadd = self.sock.accept()
            print "accept a connect..."
            Reader(client).start()
            cltadd = cltadd
            print "accept a connect(new reader..)"

lst  = Listener(7890)   # create a listen thread
lst.start() # then start

# Now, you can use telnet to test it, the command is "telnet 127.0.0.1 9011"
# You also can use web broswer to test, input the address of "http://127.0.0.1:9011" and press Enter button
# Enjoy it....


你可能感兴趣的:(Python)