python udp c/s 记录

server:

 

 

import sys import socket host = sys.argv[1] port = int(sys.argv[2]) 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(100) print "Got data from", address, message #cs = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #cs.sendto(message, address) #cs.close() s.sendto(message, address) except (KeyboardInterrupt, SystemExit): raise except: traceback.print_exc() 

 

client:

 

import socket import sys import time count = 0 while (count < 9): try: time.sleep(1) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.sendto("test", ("192.168.22.209", 1234)) data,addr = s.recvfrom(1024) if data: print 'received:',data,'from',addr s.close() except: print 'except'

备注一下python2.x 和 python3.x之间的变化

print("123 %d %s 123",%(123, "hello"))这个是两个版本都适合的print函数

你可能感兴趣的:(python,socket,server,import)