python多线程在socket编程中的应用(代码范例)
来源:互联网 发布:淘宝客返利是什么意思 编辑:程序博客网 时间:2024/05/01 15:14
之前在《Python实现socket信息发送和监听的简单代码示例》一文中提到过,server段处理client端发来的请求时,需要用多线程
python多线程入门起来十分容易,所以这里直接和多线程socket server一起示范:
python的thread遵从以下格式:
import threaddef 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 timeimport threadimport 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代码则随意。
0 0
- python多线程在socket编程中的应用(代码范例)
- Java Socket编程 标准范例(多线程)
- Java Socket编程 标准范例(多线程)
- Java Socket编程 标准范例(多线程)
- Java Socket编程 标准范例(多线程)
- Java Socket编程 标准范例(多线程)
- Java Socket编程 标准范例(多线程)
- Java Socket编程 标准范例(多线程)
- Java Socket编程 标准范例(多线程)
- Java Socket编程 标准范例(多线程)
- Java Socket编程 标准范例(多线程)
- Python Socket编程范例
- 条件变量 condition 在 python 多线程编程中的应用
- Select在Socket编程中的应用
- Select在Socket编程中的应用
- python多线程在渗透测试中的应用
- 多线程在网络编程中的应用
- 事件在多线程编程中的应用
- s3c2440裸机开发环境的搭建
- SQL 之Group by with Rollup 的效果
- android应用添加桌面快捷方式
- Quicksort
- 数据结构java版三 Java内置数据结构
- python多线程在socket编程中的应用(代码范例)
- 将博客搬至CSDN
- 12个乒乓球称3次,分出轻重
- 【MonogoDB】The high update operation of MongoDB
- 线性回归(Linear Regression,LR)
- malloc过程中做了那些?
- 分析JDK动态代理较好的文章
- FOJ1138 Easy Task
- Android 图片失真的原因