python udp
server.py
# -*-coding:utf-8 -*-
import socket
import sys
HOST=''
PORT=8888
try:
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
print('socket created')
except socket.error:
print('created failed')
sys.exit()
#bind socket
try:
s.bind((HOST,PORT))
except socket.error:
print('bind failed')
print('bind ok')
#keep talking with client
while True:
#server receive and send
d=s.recvfrom(1024)
data=d[0]
addr=d[1]
if not data:
break
reply='ok...'+data.decode('utf-8')
s.sendto(reply.encode('utf-8'),addr)
print('message[' +addr[0]+':'+str(addr[1])+']-'+data.strip())
s.close()
client.py
# -*-coding:utf-8 -*-
import socket
import sys
#create dgram udp socket
try:
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
except socket.error:
print('create udp failed')
sys.exit()
host='localhost'
port=8888
while True:
msg='this is client'
try:
#client send and receive
s.sendto(msg.encode('utf-8'),(host,port))
d=s.recvfrom(1024)
reply=d[0]
addr=d[1]
print('server reply:'+reply.decode('utf-8'))
except socket.error:
print('client error')
sys.exit()