码迷,mamicode.com
首页 > 编程语言 > 详细

Python网络编程笔记一

时间:2017-06-15 21:43:02      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:udp   span   客户   not   inpu   发送   cli   color   .so   

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网络编程笔记一

标签:udp   span   客户   not   inpu   发送   cli   color   .so   

原文地址:http://www.cnblogs.com/xhcdream/p/7019794.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!