1.TCP服务端案例
from socket import * from select import select import sys import time # 获取当前时间 def get_time_stamp(): ct = time.time() local_time = time.localtime(ct) data_head = time.strftime("%Y-%m-%d %H:%M:%S", local_time) data_secs = (ct - (ct)) * 1000 time_stamp = "%s.%03d" % (data_head, data_secs) return time_stamp # 创建套接字作为关注的IO s=socket() s.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) s.bind(('127.0.0.1',9988)) s.listen(5) #添加关注列表 rlist=[s,sys.stdin] wlist=[] xlist=[] # 监控关注的IO f=open('lomy.txt','a') while True: rs,ws,xs=select(rlist,wlist,xlist) # 遍历确定就绪的IO for r in rs: if r is s: #就绪,有客户端请求连接 c,addr=s.accept() print('connect from ',addr) #将客户端套接字加入关注 rlist.append(c) elif r is sys.stdin: data=sys.stdin.readline() data=get_time_stamp()+'>>>>>'+data+'\n' f.write(data) f.flush() else: data=r.recv(1024) if not data: rlist.remove(r) r.close() continue data=get_time_stamp()+'>>'+data.decode()+'\n' f.write(data) f.flush() # print('receive:',data.decode()) # r.send(b'ok thanks') #当r放入wlist表示希望主动操作r这个IO wlist.append(r) for w in ws: w.send(b'ok,Thanks') wlist.remove(w) for x in xs: pass
2.客户端代码:
from socket import * # 创建套接字 sk=socket() # 发起连接 server_addr=('127.0.0.1',9988) sk.connect(server_addr) # 收发消息 while True: data=input('>>') if not data: break sk.send(data.encode()) data=sk.recv(1024) print('from server:',data.decode()) sk.close()
不喜欢写代码,就喜欢改代码,C#/Python都可以,欢迎各位留言探讨!