-
Notifications
You must be signed in to change notification settings - Fork 12
/
udp.py
62 lines (51 loc) · 1.51 KB
/
udp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import socket
import threading
import sys
import json
# send string , to address.
def sendmbase(udp_socket, toA, message ):
udp_socket.sendto(message.encode(),(toA[0],toA[1]))
# print(message, toA)
# receive message,
# return message, and addr.
def recembase(udp_socket):
data, addr = udp_socket.recvfrom(1024)
# print(addr)
return data.decode(), addr
def sendJS(udp_socket,toA,message):
# print(toA)
sendmbase(udp_socket,toA,json.dumps(message))
def broadcastms(udp_socket,message, peers):
for p in peers.values():
sendmbase(udp_socket,p,message)
def broadcastJS(udp_socket,message, peers):
for p in peers.values():
sendJS(udp_socket,p,message)
def rece(udp_socket):
while 1:
data,addr = recembase(udp_socket)
print(data)
def send(udp_socket):
while 1:
msg = input("please input message and port:")
l = msg.split()
port = int(l[-1])
s = ' '.join(l[:-1])
toA = ('127.0.0.1', port)
sendmbase(udp_socket, toA, s)
def main():
port = int(sys.argv[1]) #从命令行获取端口号
fromA = ("127.0.0.1",port)
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_socket.bind((fromA[0],fromA[1]))
t1 = threading.Thread(target=rece, args=(udp_socket,))
t2 = threading.Thread(target=send, args=(udp_socket,))
t1.start()
t2.start()
if __name__ == '__main__':
main()
# usage:
# python p2pUdp.py 10001
# python p2pUdp.py 10002
# hello 10001
# world 10002