美文网首页
基于TCP的在线聊天室搭建

基于TCP的在线聊天室搭建

作者: sea_monster | 来源:发表于2020-05-22 12:42 被阅读0次

基于TCP的在线聊天室搭建

服务器端代码

import socket
import threading
import json

class User:
   def __init__(self, uid: int, username: str, addr: tuple):
       self.username = username
       self.uid = uid
       self.addr = addr

class ChatRoom:
   def __init__(self):
       self.users = {}
       self.conns = {}
       self.semaphore = threading.Semaphore()
       self.uid = 0
       user = User(-1, "聊天室", ())
       self.users[-1] = user

   def addUser(self, user: User, socket: socket.socket):
       self.semaphore.acquire()
       self.conns[user.uid] = socket
       self.users[user.uid] = user
       thread = threading.Thread(target=self.reveive_single_user_msg, args=(user, socket))
       thread.start()
       self.semaphore.release()


   def removeUser(self, user: User):
       self.semaphore.acquire()
       self.conns.pop(user.uid)
       self.users.pop(user.uid)
       self.semaphore.release()


   def reveive_single_user_msg(self, user: User, socket: socket.socket):
       msg = {"uid": -1, "body": user.username+"进入聊天室 ("+"在线"+ str(len(self.users.keys())-1) +"人)"}
       self.send_to_all(msg)
       try:
           while True:
               recv_data = socket.recv(1024)
               if len(recv_data) == 0:
                   self.removeUser(user)
                   break
               msg = json.loads(recv_data)
               self.send_to_all(msg)
       except:
           msg['uid'] = -1
           msg['body'] = "["+user.username+"]:"+ "退出聊天室 ("+"在线"+ str(len(self.users.keys())-2) +"人)"
           self.send_to_all(msg)
           self.removeUser(user)

   def send_to_all(self, msg: dict):
       self.semaphore.acquire()
       message = "["+self.users[msg['uid']].username+"]: "+msg['body']
       print(message)
       for key in self.conns.keys():
           try:
               if key == msg['uid']:
                   continue
           except:
               print(msg)
               continue
           msg_f = {'username': self.users[msg['uid']].username, 'body': msg['body']}
           msg_s = json.dumps(msg_f)
           try:
               self.conns[key].send(msg_s.encode("utf-8"))
           except:
               pass
       self.semaphore.release()

class Controller:
   def __init__(self, chatroom: ChatRoom):
       self.chatroom = chatroom

   def run(self):
       tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
       addr = ("", 4566)
       tcp.bind(addr)
       tcp.listen(100)
       print("==========聊天室启动==========")
       print("%s:%d" % (socket.gethostbyname(socket.gethostname()), 4566))
       while True:
           try:
               clientSocket, clientAddr = tcp.accept()
               print(clientAddr)

               msg = {"uid": self.chatroom.uid, "body": "欢迎进入聊天室\n"}
               self.chatroom.uid += 1
               msg_s = json.dumps(msg)
               clientSocket.send(msg_s.encode("utf-8"))

               # 接受用户信息传送
               userInfo = clientSocket.recv(1024)
               userInfo = json.loads(userInfo)
               user = User(userInfo['uid'], userInfo['username'], clientAddr)
               self.chatroom.addUser(user, clientSocket)
           except:
               pass
       tcp.close()


if __name__ == '__main__':
   controller = Controller(ChatRoom())
   controller.run()

客户端代码

import socket
import json
import threading

# 服务器 IP和端口
server_ip = ("47.240.94.178", 4566)
username = None
end = False
def connect(username):
    tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcp.connect(server_ip)
    msg = tcp.recv(1024)
    msg = json.loads(msg)
    print(msg['body'])
    uid = msg['uid']
    msg = {}
    msg['uid'] = uid
    msg['username'] = username
    msg_s = json.dumps(msg)
    tcp.send(msg_s.encode("utf-8"))
    thread = threading.Thread(target=receive, args=(tcp,))
    thread.start()
    while True:
        data = input("[" + username + "]:")
        data = data.split()
        if (not data[0].isnumeric()) or (int(data[0])!=0 and int(data[0])!=1):
            print("输入不合法!![:数字(0退出 1发送)  内容]")
            continue

        if (len(data) == 1) and int(data[0])==0:
            break
        if int(data[0]) == 0:
            break
        msg = {}
        if int(data[0]) == 1:
            msg['uid'] = uid
            msg['body'] = ' '.join(data[1:])
        msg_s = json.dumps(msg)
        tcp.send(msg_s.encode("utf-8"))
    tcp.close()


def receive(tcp: socket.socket):
    while True:
        try:
            msg = tcp.recv(1024)
            msg = json.loads(msg.decode("utf-8"))
            print("")
            print("["+msg['username']+"]:", msg['body'])
            print("["+username+"]:", end=" ", flush=True)
        except:
            break


if __name__ == '__main__':
    username = input("用户名:")
    username = username.strip()
    connect(username)

CharRoom.py是服务器端代码

User.py是客户端代码

自己搭建一个在线聊天室

将ChatRoom.py上传到服务器 
直接python3 ChatRomm.py运行就好了
然后将User.py的server_ip改成自己的服务ip和端口
服务器打开的防火墙端口需要和客户端的一致
发消息时
0退出 1发送  内容
如:
1 在吗? (发送“在吗?”)
0 不用   (退出)
0       (退出)

相关文章

  • 基于TCP的在线聊天室搭建

    基于TCP的在线聊天室搭建 服务器端代码 客户端代码 CharRoom.py是服务器端代码 User.py是客户端...

  • Python高级第三天

    网络编程初识 tcp聊天室 snd_tcp.py serv_tcp.py udp聊天室 snd_udp.py se...

  • WebRTC在线聊天室

    前言 之前写过关于websocket的文章《基于WebSocket的在线聊天室(一)(二)》,这次换成WebRTC...

  • 我所认识的网络

    TCP服务 TCP服务在网络应用中十分常见,目前大多数应用都是基于TCP搭建而成。 TCP的全名为传输控制...

  • 构建TCP服务

    TCP服务在网络应用中十分常见,目前大多数的应用都是基于TCP搭建而成的。 1. 什么是TCP? tcp全名叫传...

  • python进阶

    1.udp聊天室 2.tcp 2.1tcp介绍 2.1.1tcp简介 2.1.2TCP特点 2.1.3tcp通信模...

  • 基于WebSocket的在线聊天室(二)

    前言 在上一篇文章中已经对websocket的做了一定的介绍,并给出了一个文本聊天室的例子,本文将继续对其进行功能...

  • 基于WebSocket的在线聊天室(一)

    前言 去年在tomcat7自带的例子中发现了两个有趣的demo,贪食蛇游戏和画板。很有意思的是打开的几个窗口内容都...

  • 一起来做一个基于python的tcp聊天室吧

    基于python的tcp聊天室的实现 1.目标和思路 2.客户端代码 3.服务器代码 4.运行结果 1.目标和思路...

  • webrtc

    使用WebRTC搭建前端视频聊天室——入门篇使用WebRTC搭建前端视频聊天室——信令篇Android之WebRTC介绍

网友评论

      本文标题:基于TCP的在线聊天室搭建

      本文链接:https://www.haomeiwen.com/subject/mqrqahtx.html