python实现的udp协议Server和Client代码实例
更新时间:2014年06月04日 10:01:50 作者:
这篇文章主要介绍了python实现的udp协议Server和Client代码实例,需要的朋友可以参考下
直接上代码:
Server端:
#!/usr/bin/env python
# UDP Echo Server - udpserver.py
import socket, traceback
host = ''
port = 54321
s = 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端:
Server端:
复制代码 代码如下:
#!/usr/bin/env python
# UDP Echo Server - udpserver.py
import socket, traceback
host = ''
port = 54321
s = 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, sys
host = 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"
# UDP Client - udpclient.py
import socket, sys
host = 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 Opencv提取图片中某种颜色组成的图形的方法
这篇文章主要介绍了Python Opencv提取图片中某种颜色组成的图形的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2019-09-09用Anaconda安装本地python包的方法及路径问题(图文)
这篇文章主要介绍了用Anaconda安装本地python包的方法及路径问题,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2019-07-07
最新评论