Python tour fifth (ii): Python socket single thread + blocking mode

Source: Internet
Author: User

In the previous fifth (a), a socket example is a single-threaded, that is, the server can only accept a connection from a client side, in order to better illustrate the socket single-threaded and blocking mode, the following example is modified.


1. Single thread + blocking + Interactive

The previous example is single-threaded and non-interactive, and is now rewritten as interactive, that is, the end is not executed once, and the desired effect is that the data sent is entered by the user and then received by the server side.

Server side: As in the previous example, nothing has changed

import socket                  #导入socket类  host = '                        #定义侦听本地地址口 (in case of multiple IP addresses), this means listening to all, or writing 0.0.0.0port =  50007                   #Server端开放的服务端口s  = socket.socket (socket.af_inet, socket. SOCK_STREAM)      #选择Socket类型和Socket数据包类型s. Bind ((host, port))            #绑定IP地址和端口s. Listen (1)                     #定义侦听数开始侦听 (actually no effect) conn, addr = s.accept ()        #定义实例, the return value of the Accept () function can be seen above the socket function description  print  ' Connected by ' ,  addrwhile 1:    data = CONN.RECV (1024x768)      #接受套接字的数据     if not data:break           #如果没有数据接收, disconnect     print  ' REVC: ', data          #发送接收到的数据     conn.sendall (data)           #发送接收到的数据conn. Close ()                         #关闭套接字

Client side:

Import sockethost = ' 192.168.1.13 ' PORT = 50007s = Socket.socket (socket.af_inet, socket. Sock_stream) S.connect ((HOST, PORT)) While true:user_input = Raw_input (' msg to send: '). Strip () #由User输入要发送的数据s. Sendall ( user_input) data = S.RECV (1024x768) print ' Received ', repr (data) s.close ()

Demonstrate:

Step 1:server Run the server-side program

[Email protected]:/mnt/hgfs/python/day5$ Python server4.py ===> cursor is here in wait state

Step 2:client a terminal run client program

[Email protected]:/mnt/hgfs/python/day5$ Python client4.py msg to send:the first Msg. ===>user input data received ' the first Msg. ' ===>server end returns the data msg to send:the second MSG. Received ' the second Msg. ' Msg to send:the third Msg. Received ' the third Msg. ' Msg to send:i ' m a.received "I ' m A." msg to send: ===> continues to wait for user input data

Step 3: Observe the phenomenon in the server side

[Email protected]:/mnt/hgfs/python/day5/[2]sec_4_ver2 (Single threaded, interactive, blocking mode general Demo) $ Python server4.py Connected by ('    192.168.1.13 ', 52645) revc:the first Msg. ===> receives the data sent by the user revc:the second msg.revc:The third msg.revc:i ' m a.===> cursor is here in a wait state

If there is another client at this point, the B end is connected again, the following is the case:

[Email protected]:/mnt/hgfs/python/day5$ Python client4.py msg to send:i ' m b===> cursor is here in wait state

At this point, if the client a-side disconnects, the server will also close the socket, client B-side sent data still cannot be received by servers.

At this point, the server is blocked, because the service side and client A is connected, unable to receive the data sent by client B, which also shows that at this time the servers are single-threaded.


2. Single thread + blocking + Interactive Advanced presentation

Make further changes to the code in the above example to make the blocking pattern more noticeable.

Server side:

Import Sockethost = ' PORT = 50007s = Socket.socket (socket.af_inet, socket.  Sock_stream) S.bind ((HOST, PORT)) S.listen (1) while 1:conn, addr = s.accept () #在循环中接受Client端连接的请求print ' Connected by ', Addrwhile True: #再做一个内部的循环data = conn.recv (1024x768) print ' Received ', dataif not data:breakconn.sendall (dat A) Conn.close ()

Client side: the same as the code in the previous example

Import sockethost = ' 192.168.1.13 ' PORT = 50007s = Socket.socket (socket.af_inet, socket. Sock_stream) S.connect ((HOST, PORT)) While true:user_input = Raw_input (' msg to send: '). Strip () S.sendall (user_input) data = S.RECV (1024x768) print ' Received ', repr (data) s.close ()

Demonstrate:

Step 1:server Run the server-side program

[Email protected]:/mnt/hgfs/python/day5$ Python server4.py ===> cursor is here in wait state

Step 2:client a terminal run client program

[Email protected]:/mnt/hgfs/python/day5$ Python client4.py msg to send:hello! Received ' hello! ' msg to send:i ' m client a.received "I ' m client A." msg to send: ===> continues to wait for user input data

Step 3: Observe the phenomenon in the server side

[Email protected]:/mnt/hgfs/python/day5$ Python server4.py Connected by (' 192.168.1.13 ', 52647) Received hello! Received I ' m Client a.===> cursor is here in a wait state

If there is another client at this point, the B end is connected again, the following is the case:

[Email protected]-machine:/mnt/hgfs/python/day5$ Python client4.py msg to send:i ' m Client b.===> cursor is here in wait state

The state of the server side remains:

[Email protected]:/mnt/hgfs/python/day5$ Python server4.py Connected by (' 192.168.1.13 ', 52647) Received hello! Received I ' m Client a.===> cursor is here in a wait state

This attempts to disconnect the client a end:

[Email protected]:/mnt/hgfs/python/day5$ Python client4.py msg to send:hello! Received ' hello! ' msg to send:i ' m client a.received "I ' m client A." msg to Send:^ctraceback (max recent call last): File "client4.py", line ten, in <module> user_input = Raw_input ( ' Msg to send: '). Strip () Keyboardinterrupt

And look at the server side:

[Email protected]:/mnt/hgfs/python/day5$ Python server4.py Connected by (' 192.168.1.13 ', 52647) Received hello!    Received i ' m client a.received Connected by (' 192.168.1.13 ', 52648) Received i ' m client B. ===> successfully received data sent from client B-side ===> cursor is in wait state here

Take a look at the client B-side scenario:

[Email protected]:/mnt/hgfs/python/day5$ Python client4.py msg to send:i ' m client b.received "I ' m client B." msg to send: ===> cursor is in wait state here

The above phenomenon, according to the server side of the program code, it is very good to understand the single-threaded mode and blocking the details of the case, here is: the server side to accept the client A-side connection, that is, the thread to accept the connection, but still occupy the receiving and sending data threads, So the client B-side can be connected to the server side, but the data is not successfully received by the server side, when the client A-side disconnects from the server side, the server side of the receive and send data thread is immediately released, and then can receive from the client The data sent by the B-terminal.


Single-threaded, that is, the serial transmission of data, will cause blocking, the above two examples are very good demonstration of the blocking process, if you want to solve this problem, of course, on the server side need to support multi-threading, that is, data folding concurrency.

This article is from the "fragrant fluttering leaves" blog, please make sure to keep this source http://xpleaf.blog.51cto.com/9315560/1700037

Python tour fifth (ii): Python socket single thread + blocking mode

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.