SoFunction
Updated on 2024-10-30

Python3 based socket chat programming

In this article, we share an example of python3-based socket chat programming for your reference, the details are as follows

Phase I:The easiest chat system

Cons: The program is not well developed, only one round trip and no one can say more than one sentence at a time

server side:

import socket
HostPort = ('127.0.0.1',9999)
s = (socket.AF_INET,socket.SOCK_STREAM)
(HostPort)
(1)
conn,addr = ()
#print('Connecting by : %s ' % addr)
while 1:
 data = (1024).decode()
 print (data)
 user_input = input('>>>')
 (user_input.encode('utf8'))
 #()
()

client side:

import socket
hostport = ('127.0.0.1',9999)
s = (socket.AF_INET,socket.SOCK_STREAM)
(hostport)
 
while 1:
 user_input = input('>>> ').strip()
 (user_input.encode('utf-8'))
 if len(user_input) == 0:
 continue
 if user_input == 'quit':
 ()
 break
 server_reply = (1024).decode()
 print (server_reply)

Caveats:In python 3, bytes and str are two different concepts, send and recv data are bytes, and the conversion of str to bytes is realized by encode('utf8'), and the conversion of bytes to str, is realized by decode();

In that phase, the service is very unstable and often disconnects, so there is a next phase and each person can send multiple messages at a time;

Stage 2Multi-threaded concurrent chat system

In Stage 1, the communication between the server side and the client can only be a send and a receive, can not realize the server side and the client side of the two sides of the free message sending, so we refer to the multi-threading, we will be the reception of the message to open a separate thread, so that the server side and the client side can be realized at the same time to send more than one message, and does not affect the reception;

Start on the code:

server side:

import socket
import threading # Import multi-threaded modules
print("Waitting to be connected......")
HostPort = ('127.0.0.1',9999)
s = (socket.AF_INET,socket.SOCK_STREAM) # Create socket instances
(HostPort)
(1)
conn,addr = ()
true=True
addr = str(addr)
print('Connecting by : %s ' %addr )
def Receve(conn):   # Define receive as a function
 global true # Declare a global variable that is triggered when a message is received as quit true = False will close the socket
 while true:
 data = (1024).decode('utf8') 
 if data == 'quit':
 true=False
 print("you have receve: "+data+" from"+addr) # Exit the receiving thread when the received value is 'quit', otherwise, loop through and print the receiving
thrd=(target=Receve,args=(conn,)) # thread instantiation, target is the method, args are the method's arguments
()    # Starting threads
while true:
 user_input = input('>>>')
 (user_input.encode('utf8'))  # Send a message in a loop
 if user_input == 'quit':   # Close socket when sent as 'quit'
 true = False
 #()
()

client side

import socket
import threading
hostport = ('127.0.0.1',9999)
s = (socket.AF_INET,socket.SOCK_STREAM)
(hostport)
true = True
def Receve(s):
 global true
 while true:
 data = (1024).decode('utf8')
 if data == 'quit':
 true = False
 print('recevie news:\033[5;37;46m%s\033[0m' % data )
thrd=(target=Receve,args=(s,))
()
while true:
 user_input = input('>>>')
 (user_input.encode('utf8'))
 if user_input == 'quit':
 true = False
()

Effect display (purple font is receiving message, white font is sending message, either side can exit by typing 'quit')

1、Server-side:(Originally, only the server side can receive the message first before sending the message, now there is no such restriction, you can send it at any time on your own initiative))

2、Client

This is the whole content of this article.