Python Learning: Socket Programming-multi-client communication chat Room

Source: Internet
Author: User

Recently learning Python, but also need to learn some of the network programming knowledge, wrote a simple chat room program. The program is divided into two Python files, one is server.py and the other is client.py.

The process for socket programming is as follows:

  

  

Service side:

1. The server needs to create a socket object. (Socket ())

2. Bind the IP address and port number for this socket object. (Bind ())

3. Let the socket object enter the listening state, and the incoming parameter 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. (Listen ())

4. In the while true loop receives the connection request sent by the client, and the loop is blocked if there is no connection request. (Accept () whether the value is returned)

5. After the server receives the connection request sent by the client (accept () has the return value), returns a new socket object and the address of the list type, the list No. 0 item is the recorded IP, and the 1th item is the port number of the record.

6. The client then sends the specific data to the server via Send (), Sendall () and other methods, and the subsequent server communicates with the client via the new socket object returned by the Accept (). This new socket object is to be placed in a new while true loop that precedes a while true loop to get the message using recv (). (recv (), Send (), Sendall ())

  

Client:

1. The client creates a socket object. (Socket ())

2. The client initiates a connection request. (Connect ()) ====> corresponds to 4 of the service side.

3. The client sends the data. (Send (), Sendall ()) ====> corresponds to 6 of the service side.

The process of communication is described above, but some details need to be noted. The socket communication is passed by byte, and the string needs to be encoded into byte type by encode () to transmit. The receiving end needs to decode byte through decode () to convert to a string. If you are transferring an object, you need to import the Pickle module, which is converted to a type that can be transferred by Pickle.dumps (object) and restored back to the object by Pickle.loads (object).

  

In order to realize the function of multi-client connection, multithreading is introduced. Whenever a client initiates a connection, a new thread is created, and the thread is responsible for communicating with the client. This enables multi-threaded communication. UserList is a list that adds a pair of connected sockets to the list whenever a client connects to the server. After this thread receives the information sent by the client, it iterates through each element of the list, enabling each client to forward messages sent by that client.

1  while True: 2     conn, addr = socket_server.accept ()3     #  Conn is a new socket object, and subsequent operations connected to the server are handled by conn  4     userdict[conn] = addr5    userlist.append (conn)6      thread = Threading. Thread (Target=newclientconnection, args=(conn, addr))7     Thread.Start ()

  

1   while True: 2         Words_byte = Conn.recv (1024x768)3         words = words_byte.decode ()4          Print(words)5for in           userlist:6             C.sendall (Words.encode ())

In order to enable clients to receive messages sent by other clients, and to send new messages multiple times, you need to create two threads, one for receiving messages, and one for sending messages.

1 thread_send = Threading. Thread (Target=sendmessage, args=(socket_client, name))2thread_send.start ()3 Thread_receive = Threading. Thread (Target=receivemessage, args=(socket_client,))4 Thread_receive.start ()

def sendMessage (socket_client, name):      while True:         = input ()        "  :   " + words        socket_client.sendall ( Message.encode ())

def receiveMessage (socket_client):      while True:         = Socket_client.recv (1024x768)        = datafromserver_byte.decode ()        print(str)

Note that when the threading module creates a thread, "target=" needs to fill in the function name, "args=" needs to fill in the function's parameters, and is filled in as a tuple, if there is only one argument, you need to add a "," to the parameter.

Summary of Git knowledge in the project:

Get the version of the historical commit code

git log #查看历史提交记录和版本号git Branch new branch name version number #创建新分支, and the new branch is the version number corresponding to the version of the Code git checkout new branch name # Switch to the new branch            

  

Merge local version other branches to master branch

git checkout mastergit Merge branch name

Python Learning: Socket Programming-multi-client communication chat Room

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.