10.python Network Programming (Startin Part 1)

Source: Internet
Author: User

A. What is a socket?

Socket is to achieve the C/s architecture, the socket is located between the application layer and the transport layer, is the transport layer and the application layer between the interface, it is the complex TCP/IP protocol family hidden behind the socket interface, for the user, a simple set of interfaces is all, Let the socket to organize the data to conform to 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 requirements of the socket to program, write the program naturally follow the TCP/UDP standard.

Some people also say that the socket is used to identify the location of a host in the Internet, and port is used to identify an application on this machine, the IP address is configured on the network card, and the port is the application Ip+port,ip, The IP-to-port binding identifies an application that is unique to the Internet.

Add: Someone will confuse the socket with the PID of the program, the PID of the program is the identity of different processes or threads on the same machine.


Two. Socket type.

    1. File-based sockets.

      Af_unix: File-based sockets, that is, through the underlying file system to fetch data, two sockets process running on the same machine, you can access the same file system to achieve communication between the two programs.

    2. Network-based sockets.

Three. Socket workflow.

650) this.width=650; "src=" http://images.cnblogs.com/cnblogs_com/goodcandle/socket3.jpg "width=" 478 "height=" 491 " Hspace= "0"/>

The TCP server establishes the connection process:

The socket () instantiates a Socket object →bind () bound IP address and Port →listen () begins to listen for the previously bound IP address and Port →accept () begins to passively receive connections from the TCP client, and will wait until the connection arrives (if there is no connection, it will wait, Until a client is connected.

The TCP client establishes the connection process:

The socket () client also initializes a socket object →connect () actively connects to the server (actively initializing the connection to the TCP servers) if the connection succeeds, the client and server can send and receive data to each other. (In fact, connect is the equivalent to respond to the server's accept, the server's accept has been waiting for the client to connect)

The client sends the data request, the server receives the request and processes the request, then sends the response data to the client, the client reads the data, closes the connection, and ends the interaction at the end.



Four. Usage of the socket module.

Import socket

Socket.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 Sockets

Tcpsock = Socket.socket (socket.af_inet, socket. SOCK_STREAM)

Get UDP/IP sockets

Udpsock = Socket.socket (socket.af_inet, socket. SOCK_DGRAM)

Because there are too many properties in the socket module. We made an exception here by using the ' from module import * ' statement. With the ' from socket import * ', we take all the attributes in the socket module into our namespace, which can greatly reduce our code.

For example Tcpsock = socket (af_inet, SOCK_STREAM)


Service-side common socket method:

S.bind (): Bind (host, port number) to socket.

S.listen (): Starts TCP snooping. #listen方法中可以指定一个backlog参数, this parameter is used to set the size of the TCP connection pool, which is supplemented by knowledge about the TCP connection pool and the three-time handshake. )

S.accept (): Passively accepts a TCP client connection, (blocking) waits for a connection to arrive.


The client uses a dedicated socket method:

S.connect (): Active initialization of TCP server connections

S.CONNECT_EX (): Extended version of the Connect () function, which returns an error code instead of throwing an exception when an error occurs.


Common socket methods that both the client and the service side have:

S.RECV (): Receives TCP data. #需要指定每次收多少字节.

S.send (): Send TCP data, #发送TCP数据 (send data is lost when the amount of data to be sent is greater than the remaining space in the peer buffer)

S.sendall (): Sends the TCP data, sends the complete TCP data (essentially is the cyclic call Send,sendall when the amount of data to be sent is greater than the remaining space in the peer buffer, the data is not lost, the loop calls send until the end of the send) (personal analysis, essentially called loop)

S.recvfrom (): Receive UDP data

S.sendto (): Send UDP data

S.getpeername (): Address to the remote end of the current socket

S.getsockname (): Address of the current socket

S.getsockopt (): Returns the parameters of the specified socket

S.setsockopt (): Sets the parameters for the specified socket

S.close (): Close socket


Five. Socket usage example.

Service side:

#!/usr/bin/python2.7

#-*-Coding:utf-8-*-

Import socket

Address_and_port = (' 127.0.0.1 ', 8888)

S1 = Socket.socket (family=socket.af_inet,type=socket. SOCK_STREAM)

S1.bind (Address_and_port)

S1.listen (3)

CONN,ADDR = S1.accept () #执行了socket的accept方法后, starts blocking and waits for the client to connect.

#执行了accept方法后, a meta-ancestor is returned, which contains a client's connection object, as well as the client's IP address and port.

While True:

data = CONN.RECV (1024x768) #用于接收tcp数据, the latter 1024 means that recv can receive up to 1024 bytes at a time. (Execution to Recv, if the peer does not send the data, or the content is empty, the program will block, do not continue to execute down.) )

Print data

Conn.send (Data.upper ())

Conn.close () #关闭与客户端的连接

S1.close () #关闭服务端套接字连接


Client:

#!/usr/bin/python2.7

#-*-Coding:utf-8-*-

Import socket

S1 = Socket.socket (socket.af_inet,socket. SOCK_STREAM)

S1.connect (' 127.0.0.1 ', 8888)

While True:

msg = Raw_input (">>>"). Strip ()

S1.send (Msg.encode (' Utf-8 '))

Print "The client has sent data!"

data = S1.RECV (1024)

Print data

#上面两个代码, you can easily understand the workflow of the next socket.


Six. Resolve problems such as sockt Communication client disconnection service-side crashes (connection loops, communication loops, and exception snaps)

Service side:

#!/usr/bin/python2.7

#-*-Coding:utf-8-*-

Import socket

Address_and_port = (' 127.0.0.1 ', 8888)

S1 = Socket.socket (family=socket.af_inet,type=socket. SOCK_STREAM)

S1.bind (Address_and_port)

S1.listen (3)

While True: #此处问连接循环, loops, and so on.

CONN,ADDR = S1.accept () #执行了socket的accept方法后, starts blocking and waits for the client to connect.

#执行了accept方法后, a meta-ancestor is returned, which contains a client's connection object, as well as the client's IP address and port.

While True: #数据传输循环

Try: #防止客户端断开导致的服务断抛异常.

data = CONN.RECV (1024x768) #用于接收tcp数据, the latter 1024 means that recv can receive up to 1024 bytes at a time.

If not data:

Break

Print data

Conn.send (Data.upper ())

Except Exception:

Break

Conn.close () #关闭与客户端的连接

S1.close () #关闭服务端套接字连接


Client:

#!/usr/bin/python2.7

#-*-Coding:utf-8-*-

Import socket

S1 = Socket.socket (socket.af_inet,socket. SOCK_STREAM)

S1.connect (' 127.0.0.1 ', 8888)

While True:

msg = Raw_input (">>>"). Strip ()

If not msg: #防止客户端发送空数据

Continue

S1.send (Msg.encode (' Utf-8 '))

Print "The client has sent data!"

data = S1.RECV (1024)

Print data

S1.close ()


#以上是防止服务端崩溃的一些解决方法.






Seven. About UDP sockets.

Service-side approximate operation process:

SS = socket () #创建一个服务器的套接字

Ss.bind () #绑定服务器套接字

Inf_loop: #服务器无限循环

cs = Ss.recvfrom ()/ss.sendto () # dialog (Receive and send)

Ss.close () # Close server sockets



The client's approximate operating flow:

CS = socket () # Create a client socket

Comm_loop: # Communication loop

Cs.sendto ()/cs.recvfrom () # Dialog (send/Receive)

Cs.close () # Close client sockets


The following is a simple example of a UDP socket:

Example 1:

Service side:

Import socket

Udp_server = Socket.socket (socket.af_inet,socket. SOCK_DGRAM)

Udp_server.bind (' 127.0.0.1 ', 8888)

While True:

MSG,ADDR = Udp_server.recvfrom (1024)

Print msg, addr

Udp_server.sendto (Msg.upper (), addr)


Client:

Import socket

Udp_client = Socket.socket (socket.af_inet,socket. SOCK_DGRAM)

While True:

msg = Raw_input (">>:"). Strip ()

If not msg:

Continue

Udp_client.sendto (Msg.encode (' Utf-8 '), ("127.0.0.1", 8888))

BACK_MSG,ADDR = Udp_client.recvfrom (1024)

Print Back_msg.decode (' Utf-8 '), addr



Eight. You need to know about TCP sockets and UDP sockets.

    1. First, there are a few things to be clear!

      1.1 All send and receive messages, are operating their own TCP/UDP buffer, sending the message is to send the data into its own buffer, the receiving message is also collected from the buffer.

      1.2 TCP uses Send to send messages, use RECV to receive messages

      1.3UDP use SendTo to send messages, use Recvfrom to receive messages

    2. TCP and UDP

      2.1 TCP is stream-based, and UDP is based on the reported

2.2 When sending a data stream using send, if the stream is empty, then TCP buffer (buffer) is also empty and the operating system does not control the TCP packet.

Sendinto (Bytes_data,ip_port): Send a datagram, Bytes_data is empty, and ip_port, all even send empty bytes_data, the datagram is not empty, their own buffer to receive the contents of the end, The operating system will control the UDP protocol packet.

3. Additions to TCP

TCP is based on link traffic:

Based on the link, the listen is required, specifying the size of the half-connection pool

Based on the link, the server must run first, and then the client initiates the link request

For Mac Systems: If one end of the link is broken, the other end of the link is also finished recv will not block, received is empty (workaround is: The service side after receiving the message plus if judgment, the empty message will break off the communication loop)

For Windows/linux Systems: If one end of the link is broken, then the other end of the link is also finished recv will not be blocked, received is empty (workaround is: server-side communication loop with exception handling, catch the exception after the break off the communication loop)


UDP communication.

No links, so no listen, no more connection pool

No link, UDP sendinto do not have a running server, you can kept the message, but the data is lost

Recvfrom the data received is less than the data sent by Sendinto, the data is lost directly on Mac and Linux system, and it is sent on the Windows system more direct error than received

Only sendinto send data without recvfrom data, data loss.


Attention:

1. You run the above UDP client alone, you find that will not error, but TCP will be error, because the UDP protocol is only responsible for sending out the package, the other side can not receive, I do not care, and TCP is based on the link, must have a service side first run, The client goes to establish a link with the server and then relies on the link to deliver the message, and any attempt to destroy the link will cause the other program to crash.

2. Above UDP program, you note any one client's sendinto, the service side will be stuck, why? Because the service side has several recvfrom to correspond several sendinto, even if is Sendinto (b ") that also must have.


This article is from the "Rebirth" blog, make sure to keep this source http://suhaozhi.blog.51cto.com/7272298/1922917

10.python Network Programming (Startin Part 1)

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.