标签:io多路复用 描述符 error div window close his 套接字 sea
select服务端,同时关注客户端连接,客户端发送和终端输入。将客户端发送和终端输入的内容全都写入到一个文件中
【linux中】
【tcp-file-io-select-server.py】
from select import select
import sys
s = socket()
s.bind(("127.0.0.1",9999))
s.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)#设置端口可立即重用
s.listen(5)
rlist = [s,sys.stdin]
wlist = []
xlist = []
f = open(‘file.txt‘,‘w‘)
while True:
rs,ws,xs = select(rlist,wlist,xlist,3)
print("***********")
for r in rs:
if r is s:
c,addr = r.accept()
rlist.append(c)
elif r is sys.stdin:
data = r.readline()
f.write(data)
f.flush()
else:
data = r.recv(1024)
r.send(b"this is xxxx")# 给连接的套接字回复消息,不回复的话client端的recv会阻塞
if not data:
rlist.remove(r)
r.close()
else:
f.write(data.decode())
f.flush()
f.close()
【tcp-file-io-select-client.py】
from socket import *
#创建套接字
sockfd = socket()
#发起连接
sockfd.connect((‘127.0.0.1‘,9999))
while True:
#消息收发
msg = input("Msg>>")
if not msg:
break
sockfd.sendall(msg.encode())
data = sockfd.recv(1024)
print(data.decode())
sockfd.close()
【windows中】
注意,在Windows中select中不能使用systdin,
否则会报错【OSError: [WinError 10038] 在一个非套接字上尝试了一个操作。】
【tcp-file-io-select-server.py】
from socket import *
from select import select
import sys
s = socket()
s.bind(("127.0.0.1",9009))
s.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)#设置端口可立即重用
s.listen(5)
# rlist = [s,sys.stdin] # win上select不能使用sys.stdin,
# 在Windows上,底层选择函数由WinSock库提供,不处理不是源自WinSock的文件描述符 .
rlist = [s]
wlist = []
xlist = []
f = open(‘file.txt‘,‘w‘)
while True:
rs,ws,xs = select(rlist,wlist,xlist,1)
print("***********")
for r in rs:
if r is s:
c,addr = r.accept()
rlist.append(c)
# elif r is sys.stdin:
# data = r.readline()
# f.write(data)
# f.flush()
else:
data = r.recv(1024)
r.send(b"this oj")
if not data:
rlist.remove(r)
r.close()
else:
print("wanle")
f.write(data.decode())
f.flush()
f.close()
s.close()
【tcp-file-io-select-client.py】
from socket import *
#创建套接字
sockfd = socket()
#发起连接
sockfd.connect((‘127.0.0.1‘,9009))
while True:
#消息收发
msg = input("Msg>>")
if not msg:
break
sockfd.sendall(msg.encode())
data = sockfd.recv(1024)
print(data.decode())
sockfd.close()
网络:IO多路复用应用-信息输入至文件(select-tcp)
标签:io多路复用 描述符 error div window close his 套接字 sea
原文地址:https://www.cnblogs.com/longyuu/p/14238670.html