udp-使用socket发送和接收数据

 1 '''使用socket发送数据'''
 2 from socket import *
 3 
 4 #创建一个tcp socket(tcp套接字)
 5 tcp_socket=socket(AF_INET,SOCK_STREAM)
 6 #创建一个udp sockect(udp套接字)
 7 udp_socket=socket(AF_INET,SOCK_DGRAM)
 8 
 9 #准备接收方的地址
10 add=("192.168.253.1",8080)
11 
12 #要发送的内容
13 content=b'cherry-hhhhh'  #注意这里要加上b
14 # content1='宁-cherry'.encode('utf-8') #或者用encode这样写
15 content1='宁-cherry'.encode('gb2312')
16 
17 #发送到指定的电脑上
18 udp_socket.sendto(content1,add)
19 
20 #关闭套接字
21 udp_socket.close()
22 
23 
24 '''使用socket接收数据'''
25 from socket import *
26 #创建一个udp sockect(udp套接字)
27 udp_socket=socket(AF_INET,SOCK_DGRAM)
28 
29 #一般是接收方需要绑定端口
30 udp_socket.bind(('',7788)) #ip地址和端口,一般ip地址不用写,表示本机的任何一个ip
31 
32 #等待接收对方发送的数据
33 reciveData=udp_socket.recvfrom(1024) #1024表示本次接收的最大字节数
34 print(reciveData)
35 #打印结果 (b'cherry', ('192.168.253.1', 8080))  #接收发送方发送的数据、ip、端口
36 
37 content,info=reciveData
38 print(content.decode('utf-8'))#解码
39 
40 
41 #例子-创建聊天室
42 from socket import *
43 
44 def main():
45     udp_socket=socket(AF_INET,SOCK_DGRAM)
46     udp_socket.bind(('',7788))
47 
48     while True:
49         reciveData = udp_socket.recvfrom(1024)
50         print(reciveData[0].decode('utf-8'))#解码
51 
52 if __name__ == '__main__':
53     main()
54 
55 
56 #例子-echo服务器(将接收信息再原封不动返回去)
57 from socket import *
58 
59 def main():
60     udp_socket=socket(AF_INET,SOCK_DGRAM)
61     udp_socket.bind(('',7788))
62 
63     while True:
64         reciveData = udp_socket.recvfrom(1024)
65         udp_socket.sendto(reciveData[0], reciveData[1])  #将接收信息再原封不动返回去
66         print(reciveData[0].decode('utf-8'))#解码
67 
68 if __name__ == '__main__':
69     main()
70 
71 
72 #模拟QQ聊天-多线程
73 from socket import *
74 from threading import Thread
75 
76 def recveData(soc1):
77     while True:
78         recevinfoa=soc1.recvfrom(1024)
79         print(recevinfoa[0].decode('utf-8'))
80 
81 def sendData(soc1):
82     while True:
83         info=input('<<')
84         soc1.sendto(info.encode('utf-8'),("192.168.253.1",8080))
85 
86 def main():
87     soc1 = socket(AF_INET, SOCK_DGRAM)
88     soc1.bind(('',7788))    #这句话不加会报错,我也不知道为啥。而且端口号必须要使用之前没用过的不然也会报错
89     t1=Thread(target=recveData,args=(soc1,))
90     t2=Thread(target=sendData,args=(soc1,))
91 
92     t1.start()
93     t2.start()
94 
95     t1.join()
96     t2.join()
97 
98 if __name__ == '__main__':
99     main()

 

posted on 2019-08-24 15:53  cherry_ning  阅读(2291)  评论(0)    收藏  举报

导航