Python-based socket programming

Source: Internet
Author: User

Sockets are based on (TCP, UDP, IP) communication, also known as sockets

The communication process is sent by the socket processing information of the server and received by the client's socket processing information.

Sockets are also commonly referred to as "sockets," which describe IP addresses and ports, and are a handle to a chain of communication, where applications usually make requests to the network through "sockets" or respond to network requests.

Sockets originate from UNIX, and one of the basic philosophies of unix/linux is "Everything is file", and the file is operated with "open" "Read and Write" "Off" mode. Socket is an implementation of this pattern, the socket is a special kind of file, some of the socket function is the operation of it (read/write Io, open, close)

The difference between a socket and file:

The file module is "open", "Read and write" "Close" for a specified document

The socket module is "open", "Read and write" "Off" for server-side and client sockets

Socket communication is based on TCP and UDP two communication,TCP is required to connect the client and the server to communicate with each other,UDP is not required to connect directly from the unilaterally initiated , the most used or TCP

Socket Communication Process
Socket communication between the server and the client to complete the communication, the server started waiting for the client to connect, the client from the server IP and the specified port for connection communication

Create a service-side

Socket.socket () to create a socket object with three optional parameters

Socket.socket (Socket.af_inet,socket. sock_stream,0)

Parameter one: Address cluster

Socket.af_inet IPv4 (default)
Socket.af_inet6 IPV6

Socket.af_unix can only be used for single UNIX system interprocess communication

Parameter two: type

Socket. Sock_stream streaming socket, for TCP (default)
Socket. SOCK_DGRAM datagram socket, for UDP

Socket. Sock_raw the original socket, the ordinary socket can not handle ICMP, IGMP and other network messages, and Sock_raw May, second, Sock_raw can also handle special IPV4 messages, in addition, the use of the original socket, can be IP_ The HDRINCL socket option constructs an IP header by the user.
Socket. SOCK_RDM is a reliable form of UDP that guarantees the delivery of datagrams but does not guarantee the order. Sock_ram is used to provide low-level access to the original protocol, which is used when certain special operations are required, such as sending ICMP packets. Sock_ram is typically used only by advanced users or by programs that are run by administrators.
Socket. Sock_seqpacket Reliable Continuous Packet service

Parameter three: protocol

0 (default) protocol related to a particular address family, if 0, the system will automatically select an appropriate protocol based on the address format and socket category.

How to use: Object variable = socket.socket ()

Format: a = Socket.socket ()

Bind () Set server-side IP and port on server

How to use: Object variables. bind (meta-ancestor type of server IP and port)

Format: A.bind (' 127.0.0.1 ', 9999)

Listen () Listening IP and port, setting a parameter that indicates the maximum number of connections queued

How to use: Object variables. Listen (number of queues)

Format: A.listen (5)

Accept () waits for the client to receive the request, once the client requests the connection, will return two values, one is the connection object, one is the client's address information, therefore needs two variables to receive

Note: theaccept () is blocked, meaning that the program execution band here is the wait state, in the absence of a client request connection, the following code will not be executed, only the client requests the connection when the following code will be executed

Accept () is interrupted once after being connected by the client and can write a while loop to wait for the client to connect forever

How to use: Define a connection variable, define the client address information variable = object variable. Accept ()

Format: b, C = a.accept ()

#!/usr/bin/env python#-*-Coding:utf8-*-"""Create a service-side"""ImportSocket#Import ModuleA = Socket.socket ()#creating a Socket objectA.bind (('127.0.0.1', 9999,))#Binding server-side IP and PortsA.listen (5)#listen for IP and port, set a parameter that indicates the maximum number of connections queued whileTrue:#accept () is interrupted once after being connected by the client, write a while loop and let it wait for the client to connect foreverB, C = a.accept ()#waiting for the client to receive the request, once a client requests a connection, it will return two values, one is the connection, one is the client's address information, so two variables are required to receive    Print(b, C)#Print out Client connection, connection, and customer service address information

Based on the above, a socket server waiting for client connection is created.

Create Client

Connect () Connect the server side, bind the server IP and port on the client side

How to use: Object variables. socket ( meta-ancestor type of server IP and port )

Format: Z.connect ((' 127.0.0.1 ', 9999,))

Close () Closes the connection on the client

How to use: Object variables. Close ()

Format: Z.close ()

# !/usr/bin/env python # -*-Coding:utf8-*- """ Create client """ Import # Import Module # Create socket Object z.connect (('127.0.0.1', 9999,))# Connect to the server, The client binds the server side IP and Port # on the client to close the connection

Client-to-server interaction information

# !/usr/bin/env python # -*-Coding:utf8-*- """ Create a service-side """ Import # Import Module a = Socket.socket (
Socket.af_inet,socket. SOCK_STREAM)
)#creating a Socket objectA.bind (('127.0.0.1', 9999,))#Binding server-side IP and PortsA.listen (5)#listen for IP and port, set a parameter that indicates the maximum number of connections queued  whileTrue:#accept () is interrupted once after being connected by the client, write a while loop and let it wait for the client to connect foreverB, C = a.accept ()#waiting for the client to receive the request, once a client requests a connection, it will return two values, one is the connection, one is the client's address information, so two variables are required to receiveB.sendall (Bytes ("Hello, welcome!", encoding='Utf-8'))#receives client Connection object information according to accept (), sends information to the client  whileTrue:#when the client connection succeeds, it enters the loop and keeps communication with the client.j = B.RECV (1024)#receiving information from the clientJ2 = Str (j, encoding='Utf-8')#converts the received client information to a string Print(J2)ifJ2 = ="Q":#determine the client input Q, indicating no longer communicating with the server, jumping out of the loop, not keeping the client's communication  Breakb.sendall (bytes (J2+"Good", encoding='Utf-8'))#Add a good word to the client and send the message to the client

client-to-server interaction information

#!/usr/bin/env python#-*-Coding:utf8-*-"""Create a service-side"""ImportSocket#Import ModuleA = Socket.socket ()#creating a Socket objectA.bind (('127.0.0.1', 9999,))#Binding server-side IP and PortsA.listen (5)#listen for IP and port, set a parameter that indicates the maximum number of connections queued whileTrue:#accept () is interrupted once after being connected by the client, write a while loop and let it wait for the client to connect foreverB, C = a.accept ()#waiting for the client to receive the request, once a client requests a connection, it will return two values, one is the connection, one is the client's address information, so two variables are required to receiveB.sendall (Bytes ("Hello, welcome!", encoding='Utf-8'))#receives client Connection object information according to accept (), sends information to the client     whileTrue:#when the client connection succeeds, it enters the loop and keeps communication with the client.j = B.RECV (1024)#receiving information from the clientJ2 = Str (j, encoding='Utf-8')#converts the received client information to a string        Print(J2)ifJ2 = ="Q":#determine the client input Q, indicating no longer communicating with the server, jumping out of the loop, not keeping the client's communication             Breakb.sendall (bytes (J2+"Good", encoding='Utf-8'))#Add a good word to the client and send the message to the client
#!/usr/bin/env python#-*-Coding:utf8-*-"""Create client"""ImportSocket#Import Modulez = Socket.socket ()#creating a Socket objectZ.connect (('127.0.0.1', 9999,))#Connect server side, bind server IP and port on clientF = z.recv (1024)#the client receives the information from the server Sendall (), 1024 indicates the maximum receive 1024 bytesF2 = str (f, encoding='Utf-8')#converts the received service-side byte information to a stringPrint(F2)#print out the information sent from the service side whileTrue:#when the connection server is successful, it enters the loop and maintains communication with the server.A = input ("Please enter information") Z.sendall (bytes (a,encoding='Utf-8'))#sending information to the server    ifA = ="Q":#determine the client input Q, no longer jump out of the loop with service-side communication         BreakJS= Z.RECV (1024)#receive information from the service sideJS2 = str (js, encoding='Utf-8')#converts information from a service-side to a string    Print(JS2) z.close ()#Close the connection on the client

Python-based socket programming

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.