python实现的udp协议Server和Client代码实例
程序员文章站
2022-06-20 15:28:58
直接上代码:server端:复制代码 代码如下: #!/usr/bin/env python # udp echo server - udp...
直接上代码:
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写的一个简单DNS服务器实例
下一篇: 楼主正吃工作餐呢