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

时间:2021-05-22

直接上代码:
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"

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章