总结:
1.使用原生socket库,可以知道底层具体实现细节。在此基础上python封装实现细节,提供更好用的TCPServer,ThreadingTCPServer
2.为测试服务端功能,使用linux nc命令,号称“网络应用的瑞士军刀“ (用法: nc ip地址 端口 )
1. socket原生API(单客户端):
编写网络程序服务端有五步:
1.创建socket对象
2.绑定地址和端口
3.监听
4.接受请求
5.关闭请求连接
from socket import *
#主机地址
myhost=""
#端口
myport=9000
#创建Socket对象
socketObj=socket(AF_INET,SOCK_STREAM)
#绑定端口
socketObj.bind((myhost,myport))
#允许64个连接
socketObj.listen(64)
#一直运行
while True:
connection,address=socketObj.accept()
print("connect:",address)
while True:
#接收数据
data=connection.recv(1024)
print(data)
if not data:
break
#处理数据,返回给发送端
connection.send(data.upper()+b" ")
#关闭连接
connection.close()
2.TCPServer(单客户端)
from socketserver import TCPServer,BaseRequestHandler
class MyRequestHandler(BaseRequestHandler):
def handle(self):
print("connection:",self.client_address)
while True:
data=self.request.recv(1024)
if not data:
break
self.request.send(data.upper()+b" ")
if __name__=='__main__':
myHost=""
myPort=9191
serverObj=TCPServer((myHost,myPort),MyRequestHandler)
serverObj.serve_forever()
3.ThreadingTCPServer(多客户端)
from socketserver import ThreadingTCPServer,StreamRequestHandler
class MyStreamRequestHandler(StreamRequestHandler):
def handle(self):
print("connection:",self.client_address)
while True:
data=self.request.recv(1024)
if not data:
break
self.request.send(data.upper()+b" ")
self.request.close()
if __name__=='__main__':
myHost=""
myPort=9292
serverObj=ThreadingTCPServer((myHost,myPort),MyStreamRequestHandler)
serverObj.serve_forever()