The UDP server is not connection-oriented, so you do not have to do as many setup work as a TCP server. In fact, there's no need to set anything, just wait for the connection to come in.
SS = socket () # Create a server Socket Ss.bind () # BIND server socket Inf_loop: # server Infinite loop cs = Ss.recvfrom ()/ss.sendto () # Dialog (Receive and send) Ss.close () # Close Server sockets
Server-side:
From socket import *from time import ctimeudpsock=socket (af_inet,sock_dgram) #参数SOCK_DGRAM对应的是UDP协议 name= GetHostName () Port=12348udpsock.bind ((Name,port)) while True: print ("Waiting for Access") Data,addr=udpsock.recvfrom ( 1024x768) #与TCP的区别. Because you do not need to establish a link beforehand, you need to get the address of the client and send the message at any time by address print (str (addr) + "plugged in") Data= (Data.decode ("UTF-8") +ctime ()). Encode ("UTF-8") Udpsock.sendto (DATA,ADDR) #向客户端发送消息UdpSock. Close ()
Client:
#coding =utf-8from Socket Import *import sysreload (SYS) sys.setdefaultencoding (' UTF8 ') host= "192.168.1.66" port= 12348udpsock=socket (Af_inet,sock_dgram) while True: data=raw_input ("Fast Typing:") if not data: Break Udpsock.sendto (data, (Host,port)) #无需connect, direct access to host Data,addr=udpsock.recvfrom (1024x768) print via host IP and Port (Data.decode ("UTF-8")) Udpsock.close ()
Previous: Python Network programming-----TCP-based Python simple server
Next talk
If you have any questions, welcome to my public question ~
Python network programming----UDP-based python simple server