网络编程
python软件下载
socket
OSI七层模型
TCP/IP四层模型:
应用层–>http,ftp,telnet,smtp
传输层–>tcp/udp
网际层(ip)–>ip数据包分组,路由选择
网络接口层–>数据帧发送接收,处理物理信号
socket 套接字是对TCP/IP网络模型封装,可以简单的实现计算机网络中两台主机的通信
常用的地址簇:family
socket.AF_INET ipv4
socket.AF_INET6 ipv6
常用的传输协议类型type
socket.SOCK_STREAM TCP
socket.SOCK_DGRAM UDP
TCP传输:面向连接的、可靠的、字节流的传输协议
UDP传输:无连接、不可靠的、数据报的传输
socket实现基于TCP的循环服务模型
#server.py
import socket
#instantiate server socket
server=socket.socket(family=socket.AF_INET,type=socket.SOCK_STREAM)
#release the port as soon as the programme is closed on server side
server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
#bind
server.bind(("localhost",8000))
server.listen(5)
while True:
print("waiting a connection...")
conn,addr=server.accept()
print("connection from:",addr)
#recv data bytes
while True:
data=conn.recv(1024)
if not data:
print("client disconnect")
conn.close()
break
print("recv data:",data.decode())
conn.send(b"OK")
#client.py
import socket
client=socket.socket(family=socket.AF_INET,type=socket.SOCK_STREAM)
client.connect(("localhost",8000))
while True:
msg=input("input msg>>")
if not msg:
continue
elif msg in ("exit","quit","q"):
break
else:
client.send(msg.encode())
data=client.recv(1024)
print(data.decode())
client.close()
socket实现基于UDP的循环服务模型
#server.py
import socket
server=socket.socket(family=socket.AF_INET,type=socket.SOCK_DGRAM)
server.bind(("localhost",8000))
while True:
try:
data,addr=server.recvfrom(1024)
print("recv data:",data.decode())
server.sendto(b"OK",addr)
except KeyboardInterrupt:
break
server.close()
#client.py
import socket
client=socket.socket(family=socket.AF_INET,type=socket.SOCK_DGRAM)
ADDR=("localhost",8000)
while True:
msg=input(">>")
if not msg:
continue
elif msg in ("exit","quit","q"):
break
else:
client.sendto(msg.encode(),ADDR)
data,addr=client.recvfrom(1024)
print(data.decode())
client.close()