Python network programming----UDP-based python simple server

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.