Python 3 Socket Programming

Source: Internet
Author: User

Python 3 Socket Programming one client/server architecture

The internet is the C/s architecture everywhere

1, c/s structure, that is, client/server (client/server) structure

2, in the Internet everywhere visible c/s architecture such as browser, online video, a variety of social software.

The relationship between C/s architecture and socket:

We learn sockets for the development of C/s architecture

To learn the socket must first learn the Internet protocol:

1. How to develop a C/s architecture software based on socket programming

2. c/S architecture software (software belongs to the application layer) is a network-based communication

3, the core of the network is a stack of protocols, protocol is the standard, you want to develop a network-based communication software, you must follow these standards

You can read some knowledge of network protocols.

Http://www.cnblogs.com/linhaifeng/articles/5937962.html

Second, Scoket and network Protocols

A socket is an intermediate software abstraction layer that the application layer communicates with the TCP/IP protocol family, which is a set of interfaces. In design mode, the socket is actually a façade mode, it is the complex TCP/IP protocol family hidden behind the socket interface, for the user, a set of simple interface is all, let the socket to organize data to meet the specified protocol.

So, we do not need to understand the TCP/UDP protocol, the socket has been packaged for us, we only need to follow the socket rules to program, write the program is naturally follow the TCP/UDP standard.

Third, socket

Sockets originated in the the 1970s UC Berkeley version of Unix, which is what people call BSD Unix. Therefore, sometimes people also refer to sockets as "Berkeley sockets" or "BSD sockets". Initially, sockets are designed to be used for communication between multiple applications on the same host. This is also called interprocess communication, or IPC. There are two types of sockets (or two races), which are file-based and network-based.

Socket family based on file type

Socket family name: Af_unix

Unix all files, file-based sockets are called by the underlying file system to fetch data, two sockets process running on the same machine, you can access the same file system to complete the communication indirectly

Socket family based on network type

Socket family name: af_inet

There are also af_inet6 used for IPv6, and some other address families, but they are either only used on a platform, or have been discarded, or are rarely used, or are not implemented at all, in all address families, Af_inet is the most widely used one, Python supports a variety of address families, but since we only care about network programming, most of the time I only use af_inet

Iv. Socket Usage:

First you need to import the socket module (you need to import a module using any function)

socket () moduleImportSocketsocket.socket (socket_family,socket_type,protocal=0) socket_family can be Af_unix or af_inet. Socket_type can be sock_stream or sock_dgram. Protocol is generally not filled, the default value is 0. Get TCP/IP Socket tcpsock=Socket.socket (socket.af_inet, socket. SOCK_STREAM) Get UDP/IP Socket udpsock=Socket.socket (socket.af_inet, socket. SOCK_DGRAM) Because there are too many properties in the socket module. We made an exceptional use of it here.'From module Import *'Statement. Use'From socket Import *', we took all the attributes from the socket module into our namespace, which greatly shortened our code. such as Tcpsock= Socket (af_inet, SOCK_STREAM)
socket () module

Service-Side socket functions

S.bind ()    bind (host, port number) to Socket S.listen ()  Start TCP Listener s.accept ()  passively accept TCP Client connection, (blocked) wait for connection arrival

Client socket functions

S.connect ()     actively initializes an extended version of the TCP server Connection S.CONNECT_EX ()  connect () function, returning an error code instead of throwing an exception when an error occurs

Socket functions for public use

S.RECV ()            receives TCP data S.send () sends TCP data (send data is            lost when the amount of data to be sent is greater than the remaining space in the buffer cache) S.sendall ()         sends the full TCP data ( The essence is circular call Send,sendall in the amount of data to be sent is greater than the left buffer space, the data is not lost, loop call send until the end of the Send) S.recvfrom ()        receive UDP data s.sendto ()          Send UDP data S.getpeername ()     to the remote address of the current socket S.getsockname () The address of the     current socket s.getsockopt ()      returns the parameters of the specified socket s.setsockopt ()      Set the parameter of the specified socket S.close ()           close socket

Lock-oriented socket method

S.setblocking ()     sets the blocking and non-blocking mode of sockets S.settimeout () to      set the timeout time for blocking socket operations S.gettimeout ()      to get the timeout for blocking socket operations

Functions for file-oriented sockets

S.fileno () The file descriptor for the socket ()          s.makefile ()        creates a file associated with the socket

TCP-based sockets

TCP is link-based, you must start the server, and then start the client to link the server-side SS= Socket ()#Create a server socketSs.bind ()#bind an address to a socketSs.listen ()#Monitoring LinksInf_loop:#Server Infinite loopCS= Ss.accept ()#Accept Client LinksComm_loop:#Communication Cyclecs.recv ()/cs.send ()#dialog (receive and send)cs.close ()#close the client socketss.close ()#to turn off server sockets (optional)

TCP Client

CS = socket ()    #  Create client socket cs.connect (    )#  try to connect to server Comm_loop:         # Communication Cycle cs.send ()/cs.recv ()    #  Dialog (send/Receive)cs.close ()            # Close Client sockets

The socket communication process is similar to the call process, so we use the phone as an example to implement a low version of socket communication

ImportSocketip_port=('127.0.0.1', 8080)#Calling cardBUFSIZE=1024#size of sending and receiving messagess=socket.socket (Socket.af_inet,socket. SOCK_STREAM)#buy a cell phoneS.bind (Ip_port)#Mobile Phone CardS.listen (5)#Phone Standbyconn,addr=s.accept ()#Phone Answering phone#PRINT (conn)#print (addr)Print('receive a call from%s'%addr[0]) msg=CONN.RECV (BUFSIZE)#listen to the news, obey.Print(Msg,type (msg)) Conn.send (Msg.upper ())#send a message, speakconn.close ()#Hang up the phones.close ()#Mobile phone off
Service Side
ImportSocketphone=socket.socket (Socket.af_inet,socket. SOCK_STREAM)#buy a cell phonePhone.connect (('127.0.0.1', 8080))#Binding Mobile Card #send and receive messagesPhone.send ('Hello'. Encode ('Utf-8')) Data=PHONE.RECV (1024)Print('Server Back res:<%s>'%data) Phone.close ()
Client

Plus link loops and communication loops

ImportSocketphone=Socket.socket (Socket.af_inet,socket. SOCK_STREAM) phone.setsockopt (socket. Sol_socket,socket. SO_REUSEADDR,1)#That 's it, in front of BIND plusPhone.bind (('127.0.0.1', 8080)) Phone.listen (5)Print('Server start===') whileTrue:#Link Loopsconn,client_addr=phone.accept ()Print(CONN,CLIENT_ADDR) whileTrue:#Communication Cycle        Try: Client_data=CONN.RECV (1024)            if  notClient_data: Break #for Linux Systems            #print (' has Rev ')Conn.send (Client_data.upper ())exceptException:#for Windwos             Breakconn.close () phone.close ( )
plus link loop service side

Client (can have several clients linked together after the previous one is suspended and immediately linked)

ImportSocketphone=Socket.socket (Socket.af_inet,socket. Sock_stream) Phone.connect (('127.0.0.1', 8080))#send and receive messages whiletrue:msg=input ('>>:'). Strip ()if  notMsgContinuephone.send (Msg.encode ('Utf-8')) Server_data=PHONE.RECV (1024)    Print(Server_data.decode ('Utf-8') ) Phone.close ()
plus link -by-client:

Python 3 Socket Programming

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.