分享

Python Socket 多线程

 看风景D人 2014-01-07
import sys
import socket
import time
import threading

start_time = time.time()

class mythread(threading.Thread):
    def __init__(self,threadname):
        threading.Thread.__init__(self)
        self._run_num = num

    def run(self):
        global count, mutex
        threadname = threading.currentThread().getName()

        for i in range(int(self._run_num)):
            #get lock
            mutex.acquire()
            count = count + 1
            #release lock
            mutex.release()

            mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            mysock.connect(('221.11.6.88',10020))
            mysock.send('**0#PM#0#0#0#468af015-30b1-4f4a-bce8-ebbfe2c914ce')
            rdata = mysock.recv(50)
            print  i, 'received:', rdata
            mysock.close()

if __name__ == "__main__":
    global count, mutex
    threads = []
    num = 5
    count = 1
    #create lock
    mutex = threading.Lock()
    for x in range(0, num):
        threads.append(mythread(5))
    for t in threads:
        t.start()
    for t in threads:
        t.join()

print "Elapsed Time: %s" % (time.time() - start_time)

########################################################################

最近在学python的socket编程,在网上发现了一个很好的例子程序,是一个印度人写的吧,于是在两台机器上测试了一下,很好用(稍稍作了修改)。可以用于公司内两人聊天之用,比msn聊天低调多了,不容易被老板发现哈。有兴趣的试试哦~

#server

import socket

import threading

import time

SIZE = 4

host = ''

soc = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

soc.bind((host,5432))

soc.listen(5)

class CThread(threading.Thread):

    def __init__(self,c):

        threading.Thread.__init__(self)

        self.conn = c

        self.stopIt=False

    def mrecv(self):

        data = self.conn.recv(SIZE)

        self.conn.send('OK')

        msg = self.conn.recv(int(data))

        return msg

    def run(self):

        while not self.stopIt:

        msg = self.mrecv()

        print 'recieved-> ',msg

    def setConn(con1,con2):

        dict={}

        state = con1.recv(9)

        con2.recv(9)

        if state =='WILL RECV':

            dict['send'] = con1 # server will send data to reciever

            dict['recv'] = con2

        else:

            dict['recv'] = con1 # server will recieve data from sender

            dict['send'] = con2

        return dict

    def msend(conn,msg):

        if len(msg)<=999 and len(msg)>0:

            conn.send(str(len(msg)))

        if conn.recv(2) == 'OK':

            conn.send(msg)

        else:

            conn.send(str(999))

        if conn.recv(2) == 'OK':

            conn.send(msg[:999])

        msend(conn,msg[1000:]) # calling recursive

        (c1,a1) = soc.accept()

        (c2,a2) = soc.accept()

        dict = setConn(c1,c2)

        thr = CThread(dict['recv'])

        thr.start()

        try:

            while 1:

                msend(dict['send'],raw_input())

        except:

            print 'closing'

        thr.stopIt=True

        msend(dict['send'],'bye!!!')# for stoping the thread

        thr.conn.close()

        soc.close()

#client

import socket

import threading

SIZE =4

host = 'elwin2' #server name

class client(threading.Thread):

    def __init__(self,c):

        threading.Thread.__init__(self)

        self.conn = c

        self.stopIt = False

    def mrecv(self):

        data = self.conn.recv(SIZE)

        self.conn.send('OK')

        return self.conn.recv(int(data))

    def run(self):

        while not self.stopIt:

            msg = self.mrecv()

        print 'recieved-> ',msg

        soc1 = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

        soc1.connect((host,5432))

        soc1.send('WILL SEND') # telling server we will send data from here

        soc2 = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

        soc2.connect((host,5432))

        soc2.send('WILL RECV') # telling server we will recieve data from here

    def msend(conn,msg):

        if len(msg)<=999 and len(msg)>0:

            conn.send(str(len(msg)))

        if conn.recv(2) == 'OK':

           conn.send(msg)

        else:

           conn.send(str(999))

        if conn.recv(2) == 'OK':

            conn.send(msg[:999])

        msend(conn,msg[1000:]) # calling recursive

        thr = client(soc2)

        thr.start()

        try:

        while 1:

            msend(soc1,raw_input())

        except:

            print 'closing'

        thr.stopIt=True

        msend(soc1,'bye!!') # for stoping the thread

        thr.conn.close()

        soc1.close()

        soc2.close()

########################################################################

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约