Python and production belongs only to your chat channels and it ta

Foreword

Text and images in this article from the network, only to learn, exchange, not for any commercial purposes, belongs to original author, if any questions, please contact us for treatment.

Author: Python Application Collection

PS: If necessary Python learning materials can be added to a small partner click the link below to obtain their own

http://note.youdao.com/noteshare?id=3054cce4add8a909e784ad934f956cef

Introduction Principles

In today's tutorial we will use the concept of instant messaging, instant messaging allows two or more people use the network simultaneously transmit text messages, text, voice and so on. Im generally based socket connection, the socket connection can be used to send or receive data, the general form of a combination of IP + port number.

In other words, in our example, chat parties, by the party to take responsibility "server", maintaining a socket server, waiting for incoming connections; when the other is the "client", to maintain the wait state on the server side that is It may send a request to establish the connection.

When you want to enter and ta "dark room" in the chat, there is only one party to act as a server, the other can act as a client, as a "server-side" of that person, in the micro-channel IP and port number to tell each other, you can build connections, chat in the dark room, dark room of this data will not be retained in any database (unless you own a saved database).

Service-Terminal

Chat, we sometimes encounter a message of both parties at the same time. This is called full duplex chat chat: "server" may send a message to the "client", "client" may also send a message to the "server", and allows simultaneous transmission message.

The server how to achieve full-duplex chat it? Is very simple, as long as the line of the multi-thread, the main thread for receiving a client connection, the new connection is successful two threads: a message for transmitting, for receiving a message:

First, create socket server:

. 1  Import socket
 2  Import the traceback
 . 3  # set ip and port number 
. 4 Host = '' 
. 5 Port = 51423 
 . 6  # establish socket server 
. 7 S = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
 . 8  s.bind ((Host , Port))
 . 9  s.listen () 
 10  the while True:
 . 11      # wait connector 
12 is      the try :
 13 is          clientsock, clientaddr = s.accept ()
 14      the except the KeyboardInterrupt:
 15          The raise 
16     except:
17         traceback.print_exc()
18         continue 

 

Wherein, AF_INET refers to communicate using IPv4, and refers SOCK_STREAM TCP protocol. You are free to set the port number, IP address of the server by default blank.

While loop continues to wait for user connections. If a user connection is successful, we will enter the next step, namely the establishment of sending and receiving threads:

1  # establishment receiving thread 
2 T = _thread.start_new_thread (processRecv, (clientsock,))
 . 3   
. 4  # establishment sending thread 
. 5 R & lt _thread.start_new_thread = (processSend, (clientsock,))

 

clientsock what we get socket connections, processRecv processSend respectively, and for processing the receiving information processing and transmission information:

. 1  Import _Thread 
 2  DEF processRecv (clientsock):
 . 3      "" " 
. 4      accept message
 . 5          : param clientsock: Socket connection to the client
 . 6      " "" 
. 7      the while True:
 . 8          Data = clientsock.recv (4096 )
 . 9          IF  Not len (Data) :
 10              BREAK 
. 11          Print (data.decode ( ' UTF-. 8 ' ))
 12 is      clientsock.close ()
 13 is   
14  DEF processSend (clientsock):
 15      "" " 
16      to send a message
17         :param clientsock: 客户端的socket连接
18     """
19     while True:
20         data = input("> ")
21         data = data
22         clientsock.sendall(data.encode('utf-8'))
23     clientsock.close() 

 

There is a small detail to note, SendAll socket connection function only supported types of data bytes, so we have to encode ( 'utf-8').

All server-side code that way, yes, that is so simple.

Client

The client is more simple, the main thread itself is set to accept the message, then we only need one more thread can be used to send messages. All client code as follows:

. 1  Import _Thread
 2  Import SYS
 . 3  from socket Import *
 . 4   
. 5  DEF send_message (tcpCliSock):
 . 6      "" " 
. 7      transmit information
 . 8          : param tcpCliSock: connected to the socket server side
 . 9      " "" 
10      the while True:
 . 11          Message = INPUT ( ' > ' )
 12 is          IF  Not Message:
 13 is              BREAK 
14          tcpCliSock.send (message.encode ( ' UTF-. 8 ' ))
15   
16      tcpCliSock.close ()
 . 17   
18 is  IF (len (the sys.argv) <. 3 ):
 . 19      the HOST = ' localhost ' 
20 is      PORT = 51 423
 21 is  the else :
 22 is      the HOST = the sys.argv [. 1 ]
 23 is      PORT = int (SYS. the argv [2 ])
 24   
25 BUFSIZ 1024 =
 26 is ADDR = (the HOST, PORT)
 27   
28 tcpCliSock = Socket (AF_INET, SOCK_STREAM)
 29  tcpCliSock.connect (ADDR)
 30   
31 is  # thread creating the transmission message 
32 S = _thread.start_new_thread(send_message, (tcpCliSock,))
33  
34 while True:
35     rdata = tcpCliSock.recv(BUFSIZ)
36     if not rdata:
37         break
38     print (rdata.decode('utf-8'))
39     
40 tcpCliSock.close() 

 

Which, HOST partially fill each other's IP, PORT partially fill the port number. sys.argv input parameter for these two values, for example, we will name the client file: client.py, enter cmd in:

python client.py 127.0.0.1 51423

Parameters can be passed directly to execute the script, in addition, other parts and server actually similar. Note that the received data decode it (because we made the time to encode).

Guess you like

Origin www.cnblogs.com/Qqun821460695/p/11962530.html