上代码:
Server:
1 #!/usr/bin/env python
2 # UDP Echo Server - udpserver.py
3 # code by www.cppblog.com/jerryma
4 import socket, traceback
5
6 host = ''
7 port = 54321
8
9 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
10 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
11 s.bind((host, port))
12
13 while 1:
14 try:
15 message, address = s.recvfrom(8192)
16 print "Got data from", address, ": ", message
17 s.sendto(message, address)
18 except (KeyboardInterrupt, SystemExit):
19 raise
20 except:
21 traceback.print_exc()
22
Client:
1 #!/usr/bin/env python
2 # UDP Client - udpclient.py
3 # code by www.cppblog.com/jerryma
4 import socket, sys
5
6 host = sys.argv[1]
7 textport = sys.argv[2]
8
9 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
10 try:
11 port = int(textport)
12 except ValueError:
13 port = socket.getservbyname(textport, 'udp')
14 s.connect((host, port))
15 while 1:
16 print "Enter data to transmit:"
17 data = sys.stdin.readline().strip()
18 s.sendall(data)
19 print "Looking for replies; press Ctrl-C or Ctrl-Break to stop."
20 buf = s.recv(2048)
21 if not len(buf):
22 break
23 print "Server replies: ",
24 sys.stdout.write(buf)
25 print "\n"
26
posted on 2009-07-29 16:19
老马驿站 阅读(11784)
评论(0) 编辑 收藏 引用 所属分类:
python