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()
select 加入队列的例子:
####此例子中客户端断开异常未解决
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) msg_dic = {} #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 msg_dic[conn] = queue.Queue() #初始化一个队列,后面存要返回给这个客户端的数据 else: data = r.recv(1024) print("收到的数据:",data.decode()) msg_dic[r].put(data) outputs.append(r) #放入返回的连接队列里 # r.send(data) # print("send done....") for w in writeable: #要返回给客户端的连接列表 data_to_client = msg_dic[w].get() w.send(data_to_client) #返回给客户端的源数据 outputs.remove(w) #确保下次循环的时候writeable不返回这个已经处理完的连接 for e in exceptional: if e in outputs: outputs.remove(e) inputs.remove(e) del msg_dic[e]
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()