python实现的udp协议Server和Client代码实例

现实情况远非想的那么单纯容易清晰:当优越感逐渐转为失落感甚至挫败感时,当由坚信自己是一块金子到怀疑自己是一粒沙子时,愤怒,迷茫,自卑,焦急,躁动就开始与日俱增。
直接上代码:
Server端:

#!/usr/bin/env python
# UDP Echo Server - udpserver.py
import socket, tracebackhost = ''
port = 54321s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))while 1:
try:
message, address = s.recvfrom(8192)
print "Got data from", address, ": ", message
s.sendto(message, address)
except (KeyboardInterrupt, SystemExit):
raise
except:
traceback.print_exc()

Client端:
 1 #!/usr/bin/env python
# UDP Client - udpclient.py
import socket, syshost = sys.argv[1]
textport = sys.argv[2]s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
port = int(textport)
except ValueError:
port = socket.getservbyname(textport, 'udp')
s.connect((host, port))
while 1:
print "Enter data to transmit:"
data = sys.stdin.readline().strip()
s.sendall(data)
print "Looking for replies; press Ctrl-C or Ctrl-Break to stop."
buf = s.recv(2048)
if not len(buf):
break
print "Server replies: ",
sys.stdout.write(buf)
print "\n"

以上就是python实现的udp协议Server和Client代码实例。你会在你最意料不到的某个时刻遇见某个人,一次神奇的相遇,一瞬间的心神交流,你的生活就会因此改变。更多关于python实现的udp协议Server和Client代码实例请关注haodaima.com其它相关文章!

标签: udp python