python socket Implementation Chat Room
- 2021-11-14 06:09:20
- OfStack
This article example for everyone to share python socket to achieve the specific code of chat room, for your reference, the specific content is as follows
server terminal
import socket
import json,struct
from concurrent.futures import ThreadPoolExecutor
debug = True
s = socket.socket()
s.bind(("127.0.0.1",8848))
s.listen()
clients = {}
pool = ThreadPoolExecutor(100)
def send_msg(soc, msg):
l = len(msg.encode("utf-8"))
soc.send(struct.pack("q",l))
# Send data
soc.send(msg.encode("utf-8"))
''' Used to listen for messages from clients that have established a connection '''
def task(ip,c):
while True:
l = c.recv(8)
ls = struct.unpack("q",l)[0]
data = json.loads(c.recv(ls).decode("utf-8")) # A message is received from the client. eg: data = {'to_addr':'msg':''}
print(' From %s Message of: %s'%(ip,data['msg']))
# Data sent by the client
# There are two kinds of data 1 Species are distributed to everyone Another 1 Send it to a certain person separately 1 Personal
if data.get('to_addr'): # Pass it over 1 A json Format dictionary, if this to_addr If it is not empty, send it to the target customer privately
target_ip = data["to_addr"] # From data Get the target in the dictionary ip
target_conn = clients.get(target_ip) # Obtain the target customer's conn Link
send_msg(target_conn,data['msg']) # Send a message
else:
for ip,conn in clients.items():
# if c != target_conn:
send_msg(conn,data['msg'])#data['msg']
# # Find this from the list of all clients 1 A Send it
# to_addr = data["to_addr"]
# # print(data["to_addr"],"_______________")
# soc = clients.get(to_addr)
# send_msg(soc,data["msg"])
# else:
# # Traverse all clients Send to every 1 Individual
# for k,soc in clients.items():
# # if soc != c:
# send_msg(soc,data["msg"])
while True:
''' The following code is used to detect whether there is a client connection '''
c,add = s.accept()
print("%s" % add[0]," Connect to the server !")
clients[add[0]] = c # Put ip Address as key , conn As value Deposit clients In a dictionary ,clients = {'192.188.3.4':conn Link }
if debug:
print('clients=%s'%clients)
''' The following code listens for messages from clients that have established a connection '''
pool.submit(task,add,c)
client terminal
import socket,json,struct
from threading import Thread
c = socket.socket()
c.connect(("127.0.0.1",8848))
print(" Connect to server successfully !")
def recver():
while True:
lens_bytes = c.recv(8)
lens = struct.unpack("q", lens_bytes)[0]
recv_msg = c.recv(lens).decode("utf-8")
print(recv_msg)
# Open the thread to process the received data
Thread(target=recver).start()
while True:
msg = input(">>>>:").strip() # Obstruction
if "@" in msg:
info = {"msg":msg.split("@")[0],"to_addr":msg.split("@")[1]}
else:
info = {"msg": msg}
data = json.dumps(info).encode("utf-8")
c.send(struct.pack("q",len(data)))
c.send(data)