欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python的udp的socket

程序员文章站 2022-07-14 15:52:32
...
apple:udp apple$ cat UDPClient.py 
#!/usr/bin/env python
"USAGE: %s <server> <word> <port>"
from socket import *    # import *, but we'll avoid name conflict
from sys import argv, exit
if len(argv) != 4:
    print __doc__ % argv[0]
    exit(0)
sock = socket(AF_INET, SOCK_DGRAM)
messout = argv[2]
sock.sendto(messout, (argv[1], int(argv[3])))
messin, server = sock.recvfrom(255)
if messin != messout:
    print "Failed to receive identical message"
print "Received:", messin
sock.close()
apple:udp apple$ 



apple:udp apple$ cat UDPServer.py 
#!/usr/bin/env python
"USAGE: %s <port>"
from SocketServer import DatagramRequestHandler, UDPServer
from sys import argv

class EchoHandler(DatagramRequestHandler):
    def handle(self):
        print "Client connected:", self.client_address
        message = self.rfile.read()
        self.wfile.write(message)

if len(argv) != 2:
    print __doc__ % argv[0]
else:
    UDPServer(('',int(argv[1])), EchoHandler).serve_forever()
apple:udp apple$ 
相关标签: socket python