码迷,mamicode.com
首页 > 编程语言 > 详细

python--select多路复用socket

时间:2017-03-02 23:12:12      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:bytes   接收   list   class   block   实现   inpu   com   tput   

server:

import select
import socket
import sys
import queue
import os


#create a TCP/IP socket
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.setblocking(False)

#Bind the socket to the port
server_address = (‘localhost‘,10000)
server.bind(server_address)

#Listen for incoming connections
server.listen(1000)

inputs = [server,]
outputs = []
while True:
    readable,writeable,exceptional = select.select(inputs,outputs,inputs)
    print(readable,writeable,exceptional)
    for r in readable:
        if r is server:  #代表来了一个新连接
            conn,addr = server.accept()
            print("来了一个新连接",conn,addr)
            inputs.append(conn) #是因为这个新建立的连接还没发数据过来,现在就接收的话程序就报错,
                          # 所以要想实现这个客户端发数据来时server端能知道就需要让select再检测这个conn
        else:
            data = r.recv(1024)
            print("收到的数据:",data.decode())
            r.send(data)
            print("send done....")

 client:

import socket

HOST = ‘localhost‘
PORT = 10000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
while True:
    msg = bytes(input(">>:").strip(), encoding="utf-8")
    if msg == ‘q‘.encode("utf-8"):
        exit("退出!")
    s.sendall(msg)
    data = s.recv(1024)
    print(‘Received‘,data.decode())
s.close()

 

python--select多路复用socket

标签:bytes   接收   list   class   block   实现   inpu   com   tput   

原文地址:http://www.cnblogs.com/guqing/p/6492800.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!