Python 006-python Socket Programming Detailed introduction

Source: Internet
Author: User

Turn from 22109925

Python provides two basic socket modules.

The first one is the Socket, which provides the standard BSD Sockets API.

The second is Socketserver, which provides a server-centric class that simplifies the development of Web servers.

Here is the socket module function

1. 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)

2. 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) server and client cannot send list, tuple, dictionary 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

3, Socket programming ideas

TCP Service side:

1 creating sockets, binding sockets to local IP and ports

# Socket.socket (Socket.af_inet,socket. SOCK_STREAM), S.bind ()

2 Start listening for connection #s. Listen ()

3 Enter the loop and continuously accept the client's connection request #s. Accept ()

4 then receive the incoming data, and send the data #s. recv (), S.sendall ()

5 When the transfer is complete, close the socket #s. Close ()

TCP Client:

1 creating sockets, connecting remote addresses

# Socket.socket (Socket.af_inet,socket. SOCK_STREAM), S.connect ()

2 Send data and receive data after connection # S.sendall (), S.RECV ()

3 When the transfer is complete, close the socket #s. Close ()

4, socket programming service-side code:
1234567891011121314151617181920 [email protected]:/python# catday5-socket-server.py#!/usr/bin/pythonimport socket   #socket模块importcommands   #执行系统命令模块HOST=‘10.0.0.245‘PORT=50007s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)   #定义socket类型,网络通信,TCPs.bind((HOST,PORT))   #套接字绑定的IP与端口s.listen(1)         #开始TCP监听while1:       conn,addr=s.accept()   #接受TCP连接,并返回新的套接字与IP地址       print‘Connected by‘,addr    #输出客户端的IP地址       while1:                data=conn.recv(1024)    #把接收的数据实例化               cmd_status,cmd_result=commands.getstatusoutput(data)   #commands.getstatusoutput执行系统命令(即shell命令),返回两个结果,第一个是状态,成功则为0,第二个是执行成功或失败的输出信息                iflen(cmd_result.strip()) ==0:   #如果输出结果长度为0,则告诉客户端完成。此用法针对于创建文件或目录,创建成功不会有输出信息                        conn.sendall(‘Done.‘)                else:                       conn.sendall(cmd_result)   #否则就把结果发给对端(即客户端)conn.close()     #关闭连接
5, Socket programming client code:
12345678910111213 [email protected]:/python# catday5-socket-client.py#!/usr/bin/pythonimport socketHOST=‘10.0.0.245‘PORT=50007s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)      #定义socket类型,网络通信,TCPs.connect((HOST,PORT))       #要连接的IP与端口while1:       cmd=raw_input("Please input cmd:")       #与人交互,输入命令       s.sendall(cmd)      #把命令发送给对端       data=s.recv(1024)     #把接收的数据定义为变量        printdata         #输出变量s.close()   #关闭连接

Code to view Https://github.com/hustacer/Python-socket

Python 006-python Socket Programming Detailed introduction

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.