Write a chat program to familiarize yourself with the usage of multithreading and socket in python, pythonsocket
1. Introduction
Python provides a wide range of open-source libraries to help developers quickly build their desired applications. This article describes the use of sockets and multithreading in python by writing TCP/IP-based communication programs.
2. multithreading and socket usage in python
Before writing a chat program, we should familiarize ourselves with the use of multithreading and socket in python.
2.1 Multithreading
The Thread class is provided in python to develop multi-threaded programs.
The prototype of the Thread class is as follows:
Class Thread (group = None, target = None, name = None, args = (), kwargs = {})
The constructor can be called with a keyword parameter. These parameters are:
GroupIt should be None, reserved for future extension of the Python Thread class.
TargetIs the callback object called by the run () method. The default value is None, which means no object is called.
NameIs the thread name. By default, the unique name in the form of 'thread-n' is created, where N is a relatively small decimal number.
ArgsIs the tuple of the target call parameter. The default value is ().
KwargsIs the keyword dictionary of the parameter called by the target. The default value is {}.
The Thread class also provides many methods. This article only describes one method required by the program. Readers of other methods can refer to the official help documentation of python as needed.
Start (): Start a thread
The following describes how to experiment with Thread through a simple program.
The procedure is as follows:
import threading def print_work(cunt): for i in range(cunt): print 'new thread print:',idef main(): t=threading.Thread(target=print_work,args=(10,)) t.start(); sum=0; for i in range(100): sum=sum+i print 'sum=%s' % sumif __name__=="__main__": main()
The program is relatively simple, so I will not explain it more, but there are two points worth noting.
Note:
1. import threading when using the Thread class
2. When there is only one parameter in the method parameter for multi-Thread startup, The args parameter of the instantiated Thread needs to be represented as (param1,) followed by a comma, this is because when tuple has only one element, a comma must be added to the end to prevent ambiguity.
2.2 socket usage
The following describes how to use socket in python.
Note:
1In pythonUsing socketImport socket
2When using socketAnd server and client
Server:
1. Create a tcp-based socket class
S = socket. socket (socket. AF_INET, socket. SOCK_STREAM)
WhereAF_INETThe specified ipv4 protocol can also be usedAF_INET6Specify the ipv6 protocol, whileSTREAMSpecifies the stream-oriented tcp protocol.
2, S. bind ('', 8089 ))
Bind a port number, where '123. 0.0.1 'is the IP address of the client. You can use '0. 0.0.0 'is used to bind all ip addresses in the network. 8089 is the specified port. When the port is smaller than 1024, the Administrator must have the permission to bind it.
3, S. listen (5)
Start listening parameter: indicates the maximum number of connections
4, Sock, addr = s. accept ()
Accept the connection from a client. The returned result is a socket object that maintains the connection with the client, as well as the IP address and port of the client. This method also blocks the thread until the client connection is obtained.
Client:
1, S. connect ('2017. 0.0.1 ', 80 ))
Connect to the server. 'www .baidu.com 'can also be the IP address of the server.
2, S. send ('hello ')
Send data 'Hello '. A two-way channel is created for a TCP connection. Both parties can send data to the other party at the same time. However, the coordination depends on the specific protocol.
3, S. recv (1024)
Accept the data sent by the connected peer. This method will block the current thread, so a dedicated thread is required to accept data.
Note:
After a Socket is bound to the same port, it cannot be bound to another Socket.
3. python-based chat program Process Design
The second part describes the knowledge points used by chat programs and the points to be noted. Now let's start designing the program process.
The program is divided into two parts: server and client.
The process of the server is as follows:
The user object represents the connection of a client.
Shows the class structure:
The Process Design of the client is as follows:
4. Encoding Process of chat programs
This program implements a relatively simple chat program. Because it is implemented on the console, it only allows two persons to chat, and the message encoding Delimiter is|.
4.1. Server Side
First, create a User data structure. The Code is as follows:
import socket class User: def __init__(self,skt,username='none'): self.skt=skt self.username=username def send_msg(self,msg): self.skt.send(msg) def logout(self): self.skt.close()
The server encoding is as follows:
Import sys import socketimport threading, timeimport User # global variableuserlist = [] def hand_user_con (usr): try: isNormar = True while isNormar: data = usr. skt. recv (1024) time. sleep (1) msg = data. split ('|') # analyze the message if msg [0] = 'login': print 'user [% s] login' % msg [1] usr. username = msg [1] notice_other_usr (usr) if msg [0] = 'tal': print 'user [% s] to [% s]: % s' % (usr. username, msg [1], msg [2]) send_msg (msg [1], msg [2]) # send a message to the target user, parameter 1: target user, parameter 2: message content if msg [0] = 'exit ': print 'user [% s] exit' % msg [0] isNormar = False usr. close () userlist. remove (usr) Rule T: isNormar = False # notify another user or a later friend def notice_other_usr (usr): if (len (userlist)> 1 ): print 'The two users' userlist [0]. skt. send ("login | % s" % userlist [1]. username) userlist [1]. skt. send ("login | % s" % userlist [0]. username) else: print 'the one users' def send_msg (username, msg): for usr in userlist: if (usr. username = username): usr. skt. send (msg) # program entry def main (): s = socket. socket (socket. AF_INET, socket. SOCK_STREAM) s. bind ('0. 0.0.0 ', 9999) s. listen (5) print u'waiting for connection... 'While True: sock, addr = s. accept () # Wait for the user to connect to User = user. user (sock) userlist. append (user) t = threading. thread (target = hand_user_con, args = (user,); t. start () s. close () if (_ name __= = "_ main _"): main ()
4.2 Client
The client code is as follows:
Import sys import socketimport threading, time # global variable isNormar = Trueother_usr = ''def recieve_msg (username, s): global isNormar, other_usr print 'Please waiting other user login... 's. send ('login | % s' % username) while (isNormar): data = s. recv (1024) # block the thread and accept the message msg = data. split ('|') if msg [0] = 'login': print U' % s user has already logged in, start to chat '% msg [1] other_usr = msg [1] else: print msg [0] # Process Def main (): global isNormar, other_usr try: print 'Please input your name: 'usrname = raw_input () s = socket. socket (socket. AF_INET, socket. SOCK_STREAM) s. connect ("127.0.0.1", 9999) t = threading. thread (target = recieve_msg, args = (usrname, s) t. start () handle T: print 'Connection exception' isNormar = False finally: pass while isNormar: msg = raw_input () # accept user input if msg = "exit ": isNormar = False else: if (other_usr! = ''): S. send ("talk | % s" % (other_usr, msg) # encode the message and send s. close () if _ name __= = "_ main _": main ()
The effect is as follows:
5. Conclusion
By writing the chat program, I learned how to use multithreading and socket in python. The chat program is too simple. It only implements a process of client-server-client information interaction, which is not perfect. There are still many exceptions in many places.