文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>用python实现并发连接非阻塞socket编程

用python实现并发连接非阻塞socket编程

时间:2009-03-15  来源:riverbird2005

python太方便了.许多有趣的功能他已经全部集成进去,让你的实现非常方便.在实际生活中,socket并发连接是很常见的现象,用其它语言相对麻烦一些,而用python,一切都变得非常简单.
下面是一个简单的实现.
server:

import SocketServer
from SocketServer import StreamRequestHandler
#class MyHandler(SocketServer.BaseRequestHandler):
class MyHandler(StreamRequestHandler):
    def handle(self):
        addr = self.request.getpeername()
        print 'got connection from ',addr
        self.wfile.write('thx for your connection')
        while 1:
            data_received = self.request.recv(1024)
            if not data_received: break
            print data_received
            self.request.send(data_received)
my_server = SocketServer.ThreadingTCPServer(("192.168.1.103",8000),MyHandler)
my_server.serve_forever()

client:

# Echo client program
import socket
HOST = '192.168.1.103' # The remote host
PORT = 8000 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
while True:
    client_msg = raw_input()
    if cmp(client_msg,'exit') == 0:
        break
    s.send(client_msg)
    data = s.recv(1024)
    print 'Received', repr(data)
s.close()

当然,我们看到,还是通过多线程来实现并发连接的问题.
相关阅读 更多 +
排行榜 更多 +
找茬脑洞的世界安卓版

找茬脑洞的世界安卓版

休闲益智 下载
滑板英雄跑酷2手游

滑板英雄跑酷2手游

休闲益智 下载
披萨对对看下载

披萨对对看下载

休闲益智 下载