Python Network programming socket

Source: Internet
Author: User

  Socket

An interface between the application layer and the TCP,UCP protocol, the user only needs to operate the interface, and the complex data organization work is done internally by itself.

Socket (socket) for TCP protocol:

Service side

ImportSocketsk= Socket.socket ()#Create a Socket objectSk.bind (('127.0.0.1', 8080))#bind the IP address and port toSk.listen ()#MonitorConn, Address= Sk.accept ()#Create a connection whileTrue:ret= CONN.RECV (1024)#Receive data requires a specified number of bytes received    ifret = = b'Bye': Conn.send (ret) Break    Print(Ret.decode ('Utf-8') Info= Input ('>>>'). Encode ('Utf-8') Conn.send (info)#the sending data must be of type bytesConn.close ()#Close ConnectionSk.close ()#Close Socket

Client

ImportSocketsk= Socket.socket ()#Creating SocketsSk.connect (('127.0.0.1', 8080))#connecting to the service side whileTrue:info= Input ('>>>'). Encode ('Utf-8') Sk.send (info)#Send DataRET = SK.RECV (1024)#Receive Data    ifret = = b'Bye':         Break    Print(Ret.decode ('Utf-8') ) Sk.close ()#Close Socket

Scoket (socket) for UDP protocol:

Service side

ImportSocketsk= Socket.socket (type=socket. SOCK_DGRAM)#Create a UCP socket objectSk.bind (('127.0.0.1', 8080))#binding IP and Portsmsg, Address= Sk.recvfrom (1024)#The UCP waiting to receive data must first receive dataPrint(Msg.decode ('Utf-8')) Sk.sendto (b'Hello', address)#send data to carry the address where the data is sentsk.close ()

Client

ImportSocketsk= Socket.socket (type=socket. SOCK_DGRAM)#Create a UCP socket objectIp_port = ('127.0.0.1', 8080)#specifying server-side IP and PortsSk.sendto (b'Hi', Ip_port)#send data to the specified service sideMSG, address = Sk.recvfrom (1024)#receive the returned dataPrint(Msg.decode ('Utf-8') ) Sk.close ()

  

Python Network programming socket

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.