您的位置:首页 > 编程语言 > Python开发

python多线程在socket编程中的应用(代码范例)

2014-09-24 23:38 676 查看
之前在《Python实现socket信息发送和监听的简单代码示例》一文中提到过,server段处理client端发来的请求时,需要用多线程

python多线程入门起来十分容易,所以这里直接和多线程socket server一起示范:

python的thread遵从以下格式:

import thread

def child_thread(param1, param2, ...):
#your codes here
thread.exit_thread()

def test(): #Use thread.start_new_thread() to create new threads
thread.start_new_thread(child_thread, (param1,param2,...))
thread.start_new_thread(child_thread, (param1,param2,...))

那么多线程server socket代码如下:

servermt.py

# -*- coding: cp936 -*-
import time
import thread
import socket
def timer(no, interval):
cnt = 0
while cnt<10:
print 'Thread:(%d) Time:%s/n'%(no, time.ctime())
time.sleep(interval)
cnt+=1
thread.exit_thread()

def test(): #Use thread.start_new_thread() to create 2 new threads
thread.start_new_thread(timer, (1,1))
thread.start_new_thread(timer, (2,2))

def child_connection(index, sock, connection):
try:
print "begin connecion " , index
print ("begin connecion %d" %index)
connection.settimeout(50)
#获得一个连接,然后开始循环处理这个连接发送的信息
while True:
buf = connection.recv(1024)
print ("Get value %s from connection %d: " %(buf,index))
if buf == '1':
print "send welcome"
connection.send('welcome to server!')
elif buf!='0':
connection.send('please go out!')
print "send refuse"
else:
print "close"
break;#退出连接监听循环
except socket.timeout: #如果建立连接后,该连接在设定的时间内无数据发来,则time out
print 'time out'
print ("closing connection %d" %index) #当一个连接监听循环退出后,连接可以关掉
connection.close()
#关闭连接,最后别忘了退出线程
thread.exit_thread()

'''
建立一个python server,监听指定端口,
如果该端口被远程连接访问,则获取远程连接,然后接收数据,
并且做出相应反馈。
'''
if __name__=="__main__":

print "Server is starting"
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('localhost', 8001)) #配置soket,绑定IP地址和端口号
sock.listen(5) #设置最大允许连接数,各连接和server的通信遵循FIFO原则
print "Server is listenting port 8001, with max connection 5"
index=0
while True: #循环轮询socket状态,等待访问

connection,address = sock.accept()
index+=1
#当获取一个新连接时,启动一个新线程来处理这个连接
thread.start_new_thread(child_connection, (index,sock, connection))

sock.close()



Client代码则随意。
                
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息