首页 新闻 搜索 专区 学院

python中多线程socket通信问题

0
悬赏园豆:30 [待解决问题]

如题,我想问一下,如下代码写出的TCPServer,创建多线程的server,用于与多个client通信。我可以获取到每个与之连接的client的address,但如果想要指定给某一个client发送信息,应该怎样操作呢?

server:

#创建SocketServerTCP服务器:
import SocketServer
from SocketServer import StreamRequestHandler as SRH
from time import ctime

host = 'xxx.xxx.xxx.xxx'
port = 9999
addr = (host,port)

class Servers(SRH):
    def handle(self):
        print 'got connection from ',self.client_address
        self.wfile.write('connection %s:%s at %s succeed!' % (host,port,ctime()))
        while True:
            data = self.request.recv(1024)
            if not data: 
                break
            print data
            print "RECV from ", self.client_address[0]
            self.request.send(data)
print 'server is running....'
server = SocketServer.ThreadingTCPServer(addr,Servers)
server.serve_forever()

client:

from socket import *

host = 'xxx.xxx.xxx.xxx'
port = 9999
bufsize = 1024
addr = (host,port)
client = socket(AF_INET,SOCK_STREAM)
client.connect(addr)
while True:
    data = raw_input()
    if not data or data=='exit':
        break
    client.send('%s\r\n' % data)
    data = client.recv(bufsize)
    if not data:
        break
    print data.strip()
client.close()

虚心求教,多多批评!多谢!

响^_^的主页 响^_^ | 初学一级 | 园豆:110
提问于:2015-09-28 20:41
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册