首页 > 代码库 > Python网络编程笔记一
Python网络编程笔记一
AF_INET:IPV4
AF_INET6:IPV6
套接字类型:
SOCK_STREAM:TCP
SOCK_DGRAM:UDP
创建TCP套接字,也可以不传递参数,默认创建TCP套接字
tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
下面是基于python3实现的简单的TCP服务端和客户端
TCP使用send、recv发送和接收数据
服务端:
1 import socket 2 3 HOST = "127.0.0.1" 4 PORT = 9999 5 BUFFSIZE = 1024 6 ADDR = (HOST, PORT) 7 8 tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 9 10 tcpSocket.bind(ADDR) 11 12 tcpSocket.listen(5) 13 14 while True: 15 print("watting clien connection...") 16 tcpClienSock, addr = tcpSocket.accept() 17 print("connected from:", addr) 18 while True: 19 data =http://www.mamicode.com/ tcpClienSock.recv(BUFFSIZE) 20 if not data: 21 break 22 print("i have received data: ", data) 23 sendData = http://www.mamicode.com/"hello, i have received your date: %s" % data 24 tcpClienSock.send(bytes(sendData, encoding="utf-8")) 25 tcpClienSock.close() 26 tcpSocket.close()
客户端:
1 import socket 2 3 HOST = "127.0.0.1" 4 PORT = 9999 5 BUFFSIZE = 1024 6 ADDR = (HOST, PORT) 7 8 tcpClientSock = socket.socket() 9 r = tcpClientSock.connect(ADDR) 10 print(r) 11 12 while True: 13 data = http://www.mamicode.com/input(">>") 14 if data =http://www.mamicode.com/= "q" or data =http://www.mamicode.com/= "quit": 15 break 16 tcpClientSock.send(bytes(data, encoding="utf-8")) 17 recvData =http://www.mamicode.com/ tcpClientSock.recv(BUFFSIZE) 18 if not recvData: 19 break 20 print(recvData) 21 tcpClientSock.close()
接下来是简单的UDP服务器和客户端实现
UDP使用sendto、recvfrom发送和接收数据
UDP服务器:
1 import socket 2 3 HOST = "127.0.0.1" 4 PORT = 9999 5 BUFFSIZE = 1024 6 ADDR = (HOST, PORT) 7 #UDP服务器创建套接字后,只需要绑定上IP和端口号,等待接收数据即可 8 #不需要listen和accept 9 udpSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 10 udpSocket.bind(ADDR) 11 12 while True: 13 print("watting message...") 14 data, addr = udpSocket.recvfrom(BUFFSIZE) #会返回发送者地址 15 sendData = http://www.mamicode.com/"hello, i have recv your date: %s" % data 16 udpSocket.sendto(bytes(sendData, encoding="utf-8"), addr) 17 print("receive message %s from %s" % (data, addr)) 18 udpSocket.close()
UDP客户端:
1 import socket 2 3 HOST = "127.0.0.1" # ‘localhost‘也可以 4 PORT = 9999 5 BUFFSIZE = 1024 6 ADDR = (HOST, PORT) 7 #创建套接字即可发送数据,不需要connect连接 8 udpClientSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 9 10 while True: 11 data = http://www.mamicode.com/input(">>") 12 if data =http://www.mamicode.com/= "q" or data =http://www.mamicode.com/= "quit": 13 break 14 udpClientSock.sendto(bytes(data, encoding="utf-8"), ADDR) 15 recvData, addr = udpClientSock.recvfrom(BUFFSIZE) 16 if not recvData: 17 break 18 print(recvData) 19 udpClientSock.close()
Python网络编程笔记一
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。