服务器:
1 #!/usr/bin/python 2 #enconding:utf-8 3 import sys 4 import socket 5 import select 6 import time 7 8 HOST=‘‘ 9 PORT=21234 10 ADDR=(HOST,PORT) 11 BUFSIZ=8096 12 13 SerSock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) 14 SerSock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) 15 #SerSock.setblocking(False) 16 SerSock.bind(ADDR) 17 SerSock.listen(10) 18 19 inputs=[SerSock,sys.stdin] 20 outputs=[] 21 timeout=45 22 23 24 while True: 25 tcpCliSock,addr=SerSock.accept() 26 inputs.append(tcpCliSock) 27 28 while True: 29 readyInput,readyOutput,readyException=select.select(inputs,[],[]) 30 for indata in readyInput: 31 if indata is tcpCliSock: 32 data=tcpCliSock.recv(BUFSIZ) 33 if not data: 34 break 35 print "%s from %s"%(data,addr) 36 else: 37 data=raw_input() 38 if not data: 39 break 40 tcpCliSock.send(‘[%s] %s‘%(time.ctime(),data)) 41 42 tcpCliSock.close()
客户端:
1 #!/usr/bin/python 2 import sys 3 import socket 4 import select 5 6 HOST=‘localhost‘ 7 PORT=21234 8 ADDR=(HOST,PORT) 9 BUFSIZ=8096 10 11 CliSock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) 12 CliSock.connect(ADDR) 13 14 inputs=[CliSock,sys.stdin] 15 outputs=[] 16 17 while inputs: 18 readable,writable,exceptional=select.select(inputs,outputs,inputs) 19 for s in readable: 20 if s is CliSock: 21 data=s.recv(BUFSIZ) 22 if data: 23 print "%s from server"%data 24 else: 25 continue 26 else: 27 data=raw_input() 28 if not data: 29 break 30 CliSock.send(data) 31 CliSock.close()
时间: 2024-10-22 21:08:47