python编写的一个简单的socket c/s用于发送和接受数据包
服务端代码
import socket HOST = "127.0.0.1" PORT = 5000 mySocket = socket.socket( socket.AF_INET, socket.SOCK_DGRAM ) mySocket.bind( ( HOST, PORT ) ) while 1: packet, address = mySocket.recvfrom( 1024 ) print "Packet received:" print "From host:", address[ 0 ] print "Host port:", address[ 1 ] print "Length:", len( packet ) print "Containing:" print "\t" + packet # step 4: echo packet back to client print "\nEcho data to client...", mySocket.sendto( packet, address ) print "Packet sent\n" mySocket.close()
客户端代码
import socket HOST = "127.0.0.1" PORT = 5000 mySocket = socket.socket( socket.AF_INET, socket.SOCK_DGRAM ) while 1: packet = raw_input( "Packet>>>" ) print "\nSending packet containing:", packet mySocket.sendto( packet, ( HOST, PORT ) ) print "Packet sent\n" # step 3: receive packet back from server packet, address = mySocket.recvfrom( 1024 ) print "Packet received:" print "From host:", address[ 0 ] print "Host port:", address[ 1 ] print "Length:", len( packet ) print "Containing:" print "\t" + packet + "\n" mySocket.close()