Python socket Programming (i)

Source: Internet
Author: User

Python provides two levels of access to network services:
1.Socket: The low-level network service supports the basic socket, which provides the standard BSD Sockets API, which can access all methods of the underlying operating system socket interface.
2.SocketServer: High-level Network Service Module Socketserver, which provides a server-centric class that simplifies the development of network servers.


Today, let's get an initial look at the socket module.


What is a Socket?
Socket is also called "socket", the application usually through the "socket" to the network to make a request or answer the network request, so that between the host or a computer on the process can communicate, the specific introduction can view Baidu Encyclopedia. The socket communication process is as follows:

650) this.width=650; "Src=" Http://s2.51cto.com/wyfs02/M00/8D/02/wKioL1iBxaWzbmuDAAB2kTJGTNw722.jpg-wh_500x0-wm_3 -wmp_4-s_2041463124.jpg "title=" d000baa1cd11728b45647b06cafcc3cec3fd2c4c.jpg "alt=" Wkiol1ibxawzbmudaab2ktjgtnw722.jpg-wh_50 "/>

Socket () function
In Python, we use the socket () function to create a socket with the following syntax:
Socket.socket ([family[, type[, Proto]])

Parameter meaning:
Family: The socket family can make Af_unix or af_inet
Type: The socket type can be divided into sock_stream or sock_dgram depending on whether it is connection-oriented or non-connected
Protocol: General does not fill the default is 0.


Socket invocation:


Socket type

Describe
Socket.af_unix Can only be used for single UNIX system interprocess communication
Socket.af_inet network communication between servers
Socket.af_inet6 IPv6
Socket. Sock_stream Streaming socket, for TCP
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, using the original socket, you can use the IP_HDRINCL socket option by the user constructs the IP header.
Socket. Sock_seqpacket Reliable, continuous packet service
To create a TCP Socket: S=socket.socket (Socket.af_inet,socket. SOCK_STREAM)
To create a UDP Socket: S=socket.socket (Socket.af_inet,socket. SOCK_DGRAM)





Socket object (built-in) method

Server-side sockets

S.bind () binds the address (host,port) to the socket and, under Af_inet, represents the address in the form of a tuple (host,port).
S.listen () starts TCP snooping. The backlog specifies the maximum number of connections that the operating system can suspend before rejecting the connection. This value is at least 1, and most applications are set to 5.
S.accept () passively accepts TCP client connections, (blocking) waits for a connection to arrive

Client sockets

S.connect () actively initializes the TCP server connection. The format of the general address is a tuple (hostname,port) and returns a socket.error error if there is an error in the connection.
Extended version of the S.CONNECT_EX () connect () function, which returns an error code instead of throwing an exception when an error occurs

Socket functions for public use

S.RECV () Receives TCP data, the data is returned as a string, and bufsize specifies the maximum amount of data to receive. Flag provides additional information about the message, which can usually be ignored.
S.send () Sends the TCP data, sending the data in the string to the connected socket. The return value is the number of bytes to send, which may be less than the byte size of the string.
S.sendall () sends TCP data in full and sends TCP data in full. Sends data from a string to a connected socket, but attempts to send all data before returning. Successful return none, Failure throws an exception.
S.recvform () receives UDP data, similar to recv (), but the return value is (data,address). Where data is the string that contains the received information, address is the socket addressing that sent the data.
S.sendto () sends UDP data, sends the data to the socket, address is a tuple in the form of (Ipaddr,port), and specifies the remote address. The return value is the number of bytes sent.
S.close () Close socket
S.getpeername () Returns the remote address of the connection socket. The return value is typically a tuple (ipaddr,port).
S.getsockname () returns the socket's own address. Typically a tuple (ipaddr,port)
S.setsockopt (Level,optname,value) Sets the value of the given socket option.
S.getsockopt (Level,optname[.buflen]) returns the value of the socket option.
S.settimeout (timeout) sets the timeout period for the socket operation, and timeout is a floating-point number in seconds. A value of None indicates no over-time. In general, hyper-times should be set when a socket is just created, as they may be used for connected operations (such as Connect ())
S.gettimeout () Returns the value of the current timeout, in seconds, or none if the timeout period is not set.
S.fileno () returns the file descriptor of the socket.
S.setblocking (flag) If flag is 0, the socket is set to nonblocking mode, otherwise the socket is set to block mode (the default). In nonblocking mode, if the call recv () does not find any data, or the Send () call cannot send the data immediately, the Socket.error exception is raised.
S.makefile () Create a file associated with the socket


Example one:


Server-side:

socket_server.py

#coding: Utf-8from Socket import *from multiprocessing import processmyhost= ' 127.0.0.1 ' myport = 50007socket_obj = Socket ( Af_inet,sock_stream) Socket_obj.bind ((Myhost,myport)) Socket_obj.listen (5) #5指定在拒绝连接之前 The maximum number of connections that the operating system can suspend. This value is at least 1, and most applications are set to 5. While true:connect,address = socket_obj.accept () print ' Server connected by: '%s ', ' address while True:da TA = connect.recv (1024x768) if not data:break connect.sendall (data) connect.close ()

Client:

socket_client.py

From socket import *import sys,timeserverhost= ' 127.0.0.1 ' serverport=50007socket_obj = socket (af_inet,sock_stream)    Socket_obj.connect ((Serverhost,serverport)) while true:message= ' This is socket test! ' Socket_obj.send (message) data = SOCKET_OBJ.RECV (1024x768) time.sleep (2) print ' client received:%s '% DATASOCKET_OBJ.C Lose ()

Run the server-side and client, respectively, with the following results:

[email protected] ~]# python socket_server.pyserver connected by: (' 127.0.0.1 ', 53241) [[email protected] ~]# Python sock et_client.py client received:this is socket test!client received:this are socket test!client received:this is socket tes T!client received:this is socket test!client received:this are socket test!client received:this is socket test!

As can be seen from the execution results, the client sends a message to the server every 2 seconds, "This is the socket test!", and the server replies to the client after receiving the message.


We're doing an experiment: what happens when you start two clients at the same time? You will see that the first client has the return data, and the second client does not return the data. This is because only one client is currently communicating with the server through the socket, and the second worker client is in a blocking state. When you terminate the first client, the second client will be able to receive the data.


So how do we solve this problem? Requires the socket server to handle client requests and communications in a multi-threaded manner. Python multithreaded modules can be implemented using threading, multiprocessing, and so on.


Example two: multi-threaded Socket Server (multiprocessing) multithreading


Server-side:

#!/usr/bin/python#coding:utf-8from socket import *from multiprocessing import  processmyhost= ' 127.0.0.1 ' Myport = 50007socket_obj = socket (af_inet,sock_stream) socket_ Obj.bind ((Myhost,myport)) Socket_obj.listen (5)    #5指定在拒绝连接之前, the maximum number of connections that the operating system can suspend. This value is at least 1, and most applications are set to 5. Def socketserver (socket_obj):    while true:         connect,address = socket_obj.accept ()          print  ' server connected by:  '  ,address         while true:            data =  CONNECT.RECV (1024x768)             if not  data:                 Break     &nbSp;      connect.sendall (data)          Connect.close () if __name__ ==  ' __main__ ':    jobs = []     client_num = 8    for client in range (Client_ num):         p = process (target=socketserver,args= (socket_ obj,))         jobs.append (p)          p.start ()

The

Client's code does not make any modifications, and the test is as follows:

[[email protected] ~]# python socket_server.pyserver connected by:   (' 127.0.0.1 ',  53241) server connected by:   (' 127.0.0.1 ',  53242) [[email  Protected] ~]# python socket_client.py client received: this is socket  test!client received: This is socket test!client received: This  is socket test!client received: this is socket test! [[email protected] ~]# python socket_client.py client received: this  Is socket test!client received: this is socket test!client received:  this is socket test!client received: this is socket test! [[email protected] ~]# ps -ef|grep clientroot     18204  16692  0 17:11 pts/2    00:00:00 python socket_client.pyroot     18205 16762   0 17:11 pts/3    00:00:00 python socket_client.pyroot      18208 16911  0 17:11 pts/4     00:00:00 grep client


The server side generates 8 threads waiting for the client to connect, and if the number of clients is more than 8, there will be a blocking.

This article is from the "Running Snail" blog, please make sure to keep this source http://441274636.blog.51cto.com/5054639/1893444

Python socket Programming (i)

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.