前言:网络编程主要分成udp和tcp两种,udp不需要创建连接,所以传输速度快,但不稳健,tcp需要创建连接,所以传输速度慢,但稳健,现在,大多数应用都采用tcp来进行通信。
一、UDP
1.send端
1)导包 from socket import *
2)创建udpSocket对象,udpSocket = socket(AF_INET,SOCK_DGREAM)
3)调用对象发送消息,udpSocket.sendto("hello,udp,我来了".encode("utf-8"),("你要发送的那台机器的ip地址",端口))
4)关闭udpSocket对象,udpSocket.close()
2.recive端
1)导包 from socket import *
2)创建udpSocket对象,udpSocket = socket(AF_INET,SOCK_DGREAM)
3)绑定ip和端口,udpSocket.bind(("你要接收的那台机器的ip地址",端口))
4)接收数据,udpSocket.recvfrom(1024)
5)关闭udpSocket对象,udpSocket.close()
1 from socket import * 2 3 udpSocket = socket(AF_INET,SOCK_DGRAM) 4 #使用udp发送的数据,在每一次的都需要写上接收方的ip和port,可以告诉接收方用什么方式编码 5 udpSocket.sendto("haha\n".encode("gb2312"),("172.25.6.222",8080)) 6 7 udpSocket.sendto("你好啊".encode("utf-8"),("202.193.52.52",1880))
1 #coding = utf-8 2 3 from socket import * 4 udpSocket = socket(AF_INET,SOCK_DGRAM) 5 6 udpSocket.bind((‘‘,8080)) 7 recvData = udpSocket.recvfrom(1024) 8 print(recvData[0].decode("utf-8"))
二、TCP
1.server端
1)导包 from socket import *
2)创建tcpSocket对象,tcpSocket = socket(AF_INET,SOCK_STREAM)
3)绑定ip和端口,tcpSocket.bind("server端的ip",端口)
4)监听,tcpSocket.listen(5)
5)接收client端,clientSocket,clientInfo = tcpSocket.accept()
6)将client端的请求信息进行打印,recvData = clientSocket.recv(1024),print(recvData)
2.client端
1)导包 from socket import *
2)创建tcpSocket对象,tcpSocket = socket(AF_INET,SOCK_STREAM)
3)连接server端,tcpSocket.connect("server的ip地址",端口)
4)向server端发送数据,clientSocket.send("hello,tcp,我来了".encode("utf-8"))
5)将server端返回的信息进行打印,recvData = clientSocket.recv(1024),print(recvData)
6)关闭客户端,clientSocket.close()
1 from socket import * 2 3 serverSocket = socket(AF_INET, SOCK_STREAM) 4 5 serverSocket.bind(("", 8899)) 6 7 serverSocket.listen(5) 8 9 print("-----1-----") 10 clientSocket,clientInfo = serverSocket.accept() 11 12 print("-----2-----") 13 #clientSocket 表示这个新的客户端 14 #clientInfo 表示这个新的客户端的ip以及port 15 16 recvData = clientSocket.recv(1024) 17 18 print("-----3-----") 19 print("%s:%s"%(str(clientInfo), recvData)) 20 21 clientSocket.close() 22 serverSocket.close()
1 from socket import * 2 3 clientSocket = socket(AF_INET, SOCK_STREAM) 4 clientSocket.connect(("192.168.119.153", 8989)) 5 6 #注意: 7 # 1. tcp客户端已经链接好了服务器,所以在以后的数据发送中,不需要填写对方的iph和port----->打电话 8 # 2. udp在发送数据的时候,因为没有之前的链接,所依需要 在每次的发送中 都要填写接收方的ip和port----->写信 9 clientSocket.send("haha".encode("gb2312")) 10 11 recvData = clientSocket.recv(1024) 12 13 print("recvData:%s"%recvData) 14 15 clientSocket.close()