Python网络编程笔记一

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 = tcpClienSock.recv(BUFFSIZE)
20         if not data:
21             break
22         print("i have received data: ", data)
23         sendData = "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 = input(">>")
14     if data == "q" or data == "quit":
15         break
16     tcpClientSock.send(bytes(data, encoding="utf-8"))
17     recvData = 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 = "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 = input(">>")
12     if data == "q" or data == "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网络编程笔记一的主要内容,如果未能解决你的问题,请参考以下文章

简明python教程的读书笔记

简明python教程的读书笔记

读书笔记初探下一代网络隔离与访问控制

新一代网络建设理论与实践读书笔记-云计算

python核心编程笔记----threading

python网络爬虫