python serversocket 是非阻塞的吗
2017-07-28 · 知道合伙人互联网行家
关注
展开全部
Python 利用SocketServer模块
实现网络客户端与服务器并发连接非阻塞通信
MyTCPServer.py
import SocketServer
from SocketServer import StreamRequestHandlerfrom time import ctime
host = '127.0.0.1'
port = 8001
addr = (host,port)
BUF_SIZE = 1024
class Servers(StreamRequestHandler):
def handle(self):
print 'connection from %s'%str(self.client_address)#self.wfile.write('connection %s:%s at %s succeed!' % (host,port,ctime()))while True:
try:
data = self.request.recv(1024)
if not data:
break
print "----\n%s\n[Recv]%s"%(str(self.client_address), data)self.request.send(data)
except:
break
print "disconnect %s"%str(self.client_address)print 'server is running....'
server = SocketServer.ThreadingTCPServer(addr,Servers)server.serve_forever()
MyTCPClient.py
from socket import *
host = '127.0.0.1'
port = 8001
addr = (host,port)
BUF_SIZE = 1024
client = socket(AF_INET,SOCK_STREAM)
client.connect(addr)
while True:
data = raw_input()
if data.strip() == 'exit':
break
if not data:
continue
client.send('%s\r\n'%data)
print "send:%s"%data
dataRecv = client.recv(BUF_SIZE)
print "recv:%s"%dataRecv
client.close()
实现网络客户端与服务器并发连接非阻塞通信
MyTCPServer.py
import SocketServer
from SocketServer import StreamRequestHandlerfrom time import ctime
host = '127.0.0.1'
port = 8001
addr = (host,port)
BUF_SIZE = 1024
class Servers(StreamRequestHandler):
def handle(self):
print 'connection from %s'%str(self.client_address)#self.wfile.write('connection %s:%s at %s succeed!' % (host,port,ctime()))while True:
try:
data = self.request.recv(1024)
if not data:
break
print "----\n%s\n[Recv]%s"%(str(self.client_address), data)self.request.send(data)
except:
break
print "disconnect %s"%str(self.client_address)print 'server is running....'
server = SocketServer.ThreadingTCPServer(addr,Servers)server.serve_forever()
MyTCPClient.py
from socket import *
host = '127.0.0.1'
port = 8001
addr = (host,port)
BUF_SIZE = 1024
client = socket(AF_INET,SOCK_STREAM)
client.connect(addr)
while True:
data = raw_input()
if data.strip() == 'exit':
break
if not data:
continue
client.send('%s\r\n'%data)
print "send:%s"%data
dataRecv = client.recv(BUF_SIZE)
print "recv:%s"%dataRecv
client.close()
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询