#!/usr/bin/env python
#-*-coding:utf-8-*-
#tcp 客户端import socketHOST='127.0.0.1'
POST=3214s=socket.socket()
try:s.connect((HOST,POST))data='你好!'while data:s.sendall(data.encode('utf-8'))data=s.recv(1024)print('Receive from Server:\n',data.decode('utf-8'))data=input('Please input an infor:\n')
except socket.error as err:print(err)
finally:s.close()
#!/usr/bin/env python
#-*-coding:utf-8-*-
#tcp 服务器端链接
import socketHOST=''
POST=3214s=socket.socket()
s.bind((HOST,POST))
s.listen(5)
clnt,addr=s.accept()
#客户端对象print("Client Address:",addr)while True:data=clnt.recv(1024)#从客户端接受数据if not data:breakprint("Recieve Data:",data.decode('utf-8'))#接受为二进制clnt.send(data)clnt.close()
s.close()#!/usr/bin/env python
#-*-coding:utf-8-*-
#用socketserver 框架搭建tcp服务器端import socketserver
import threading#关闭服务器,在不同的线程
def sd():if serv:serv.shutdown()#处理类
class MyHdl(socketserver.StreamRequestHandler):def handle(self):while True:data=self.request.recv(1024)print('收到数据:',data.decode('utf-8'))if data==b'bye':breakself.request.sendall(data)print('本次服务结束。')threading.Thread(target=sd).start()if __name__=='__main__':HOST=''PORT=3214#实例化服务器端serv=socketserver.TCPServer((HOST,PORT),MyHdl)#启动服务serv.serve_forever()#!/usr/bin/env python
#-*-coding:utf-8-*-
#socketserver客户端
import socketHOST='127.0.0.1'PORT=3214s=socket.socket()
s.connect((HOST,PORT))
data="你好!"
while data:s.sendall(data.encode('utf-8'))if data=='bye':breakdata=s.recv(1024)print("收到数据: ",data.decode('utf-8'))data=input('输入要发送的信息:')s.close()
#!/usr/bin/env python
#-*-coding:utf-8-*-
#socketserver rf客户端
import socketHOST='127.0.0.1'PORT=3214s=socket.socket()
s.connect((HOST,PORT))
data="你好!"
while data:data+='\n's.sendall(data.encode('utf-8'))data=s.recv(1024)print("收到数据: ",data.decode('utf-8').strip('\n'))data=input('输入要发送的信息:')s.close()#!/usr/bin/env python
#-*-coding:utf-8-*-
#用socketserver 框架搭建tcp服务器端
#用rfile,wfile读取数据
import socketserver
import threading#关闭服务器,在不同的线程
def sd():if serv:serv.shutdown()#处理类
class MyHdl(socketserver.StreamRequestHandler):def handle(self):while True:#读取一行data=self.rfile.readline()if not data:break#不包含最后的换行符print('收到数据:',data.decode('utf-8').strip('\n'))self.wfile.write(data)print('本次服务结束。')threading.Thread(target=sd).start()if __name__=='__main__':HOST=''PORT=3214#实例化服务器端serv=socketserver.TCPServer((HOST,PORT),MyHdl)#启动服务serv.serve_forever()