Python Socket Programming Introduction

Source: Internet
Author: User

I. Overview

Sockets are often referred to as "sockets", which describe IP addresses and ports, are handles to a chain of communication, and applications send requests to the network via a socket or respond to requests from the network.

Socket originated from UNIX, in Linux, Unix "All Files", for the file with open, read-write, shutdown mode to operate. The socket is an implementation of this pattern and is a special kind of file. Some of the socket functions operate on them (read Io, write io, open, close)

The difference between a socket and file:

    1. The file module is opened, read-write, and closed for a specified
    2. The socket module is open, read-write, and shut down for both server and client sockets.

The following is the connection and communication for the socket:

Simple Soccket implementation: divided into two parts 1, server-side boot 2, client connection

The server-side code is as follows:

1 ImportSocket2 3Ip_port = ("localhost", 8234)4 5SK =Socket.socket ()6 Sk.bind (Ip_port)7Sk.listen (5)8 9  whileTrue:Ten     Print("Server Waiting") OneCONN,ADDR =sk.accept () AClient_data = CONN.RECV (1024) -     Print(Client_data) -Conn.sendall ("server send data to client") theConn.close ()

The code for the client is as follows:

1 ImportSocket2Ip_port = ("127.0.0.1", 8234)3 4SK =Socket.socket ()5 Sk.connect (Ip_port)6Sk.sendall ("client sent data to server")7server_reply = SK.RECV (1024)8 Printserver_reply9Sk.close ()

    1. First, the server-side operation, waiting for the client to connect;
    2. The client connects to the server side and sends the corresponding data;
    3. Server-side reply to requested data

1, server-side operation results:

1 Server Waiting 2 client sent data to server 3 Server waiting

2. Client results:

1 server send data to client 2 3 Process finished with exit code 0

3. Use the Chrome browser access server (127.0.0.1:8234) side return code as follows:

1 Server Waiting2get/http/1.13host:127.0.0.1:82344connection:keep-Alive5Cache-control:max-age=06accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.87Upgrade-insecure-requests:18user-agent:mozilla/5.0 (Windows NT 6.1; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/46.0.2490.86 safari/537.369accept-Encoding:gzip, deflate, SDCHTenaccept-language:zh-cn,zh;q=0.8 One  A  - Server Waiting -Get/favicon.ico http/1.1 thehost:127.0.0.1:8234 -connection:keep-Alive -user-agent:mozilla/5.0 (Windows NT 6.1; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/46.0.2490.86 safari/537.36 -Accept: */* +referer:http://127.0.0.1:8234/ -accept-Encoding:gzip, deflate, SDCH +accept-language:zh-cn,zh;q=0.8

Second, explanation:

SK = 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.

Socket Type:

Socket format:

Socket (Family,type[,protocal]) creates a socket with the given address family, socket type, protocol number (default = 0).

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 function

Note the point:

    1. When TCP sends data, a TCP connection is established, so you do not need to specify an address. UDP is for non-connected, each time it is sent to specify who to send.
    2. The server and client cannot send lists, tuples, dictionaries directly. Requires a string of repr (data).

Socket function

Describe

Service-Side socket function

S.bind (Address)

Binds a socket to an address, and under Af_inet, the address is represented as a tuple (host,port).

S.listen (Backlog)

Starts listening for TCP incoming connections. 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 ()

Accepts a TCP connection and returns (Conn,address), where Conn is a new socket object that can be used to receive and send data. Address is the location of the connection client.

Client socket function

S.connect (Address)

The socket that is connected to the address. 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.

S.CONNECT_EX (adddress)

function is the same as connect (address), but successfully returns 0, the value of errno is returned.

Common socket function

S.RECV (Bufsize[,flag])

Accepts data for TCP sockets. The data is returned as a string, bufsize specifies the maximum amount of data to receive. Flag provides additional information about the message, which can usually be ignored.

S.send (String[,flag])

Send TCP data. Sends data from a string to a 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 (String[,flag])

Send 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.recvfrom (Bufsize[.flag])

Accepts data for UDP sockets. 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 (string[,flag],address)

Send UDP data. Sends the data to the socket, address is a tuple in the form of (Ipaddr,port), specifying the remote address. The return value is the number of bytes sent.

S.close ()

Close the 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 for the socket.

S.setblocking (flag)

If flag is 0, the socket is set to nonblocking mode, otherwise the socket is set to blocking mode (the default value). 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

Python Socket Programming Introduction

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.