目录

  • 项目结构
    • 服务器端
    • 客户端
    • 共有
  • 代码
    • 配置信息
    • 服务器端
      • functions.py
      • senddata.py
      • server.py
    • 客户端
      • cilpboard.py
      • listening.py
      • speaker.py
      • account.py
      • login.py
      • verification.py
      • client.py

项目结构

服务器端

  • functions.py定义基本函数
  • senddata.py发送登录信息
  • server.py是主要服务器

客户端

  • cilpboard.py读取用户粘贴板信息
  • listening.py实现朗读界面
  • speaker.py实现朗读功能 (python调用baidu-aip朗读)
  • account.py创建账号页面
  • login.py登录页面
  • verification.py生成验证码
  • client.py主要客户端

共有

  • configs.py配置信息
  • tests/test.py闲的 调试

代码

配置信息

configs.py

API = 'oZ4E0v0GvMYH4E3sr7YGWGHslpQrcd2P0qSAF8aLcOTUrSXDV2ENP1Uh'
COOKIE = '9faa7231dd6655473c28cbe7af73gawc6'
ENCODING = 'utf-8'
HOST = '127.0.0.1'
DATAPORT = 7870
SENDPORT = 7878
MAINTITLE = '飞鸽'
LOGINTITLE = '登录'
CREATETITLE = '创建账号'
THEMECOLOR = 'System Default'
ICONPATH = 'resources/icons/benefit.ico'
DATAPATH = 'datas/users.pik'
ACCEPT = 10
HIGHSIZE = 32678
CAPTCHA = 'resources/captchas/{name}.gif'
CAPTCHAFONT = 'resources/fonts/maturasc.ttf'  # 验证码字体
REQUEST = {'headers': {'mode': 'request','function': 'login','api': API},'main': {'username': '网管','password': 'benefit',}
}  # request格式
RESPONSE = {'headers': {'mode': 'response','api': API},'main': {'response': 1,'cookie': COOKIE,'info': '',}
}  # response格式
# 百度aip SDK
APPID = '15422825'
APPKEY = 'DhXGtWHYMujMVZZGRI3a7rzb'
SECRETKEY = 'PbyUvTL31fImGthOOIP5ZbbtEOGwGOoT'

服务器端

functions.py

import pickle
from configs import *
def write(data=None):if data is None:data = {'网管': 'benefit'}with open(DATAPATH, 'wb') as f:f.write(pickle.dumps(data))
def read():with open(DATAPATH, 'rb') as f:return f.read()

senddata.py

from functions import read, write
from configs import *
import socket
import time
import pickle
from threading import Threaddef login(useobj, username, password):print(username, password)users = pickle.loads(read())print(users)isok = Falseinfo = '登录成功'if users.get(username, False):if users[username] == password:isok = Trueelse:info = '密码错误'else:info = '用户名不存在'    response = RESPONSE.copy()response['main']['response'] = int(isok)response['main']['info'] = infouseobj.send(pickle.dumps(response.copy()))return isokdef create(useobj, username, password):users = pickle.loads(read())isok = Falseinfo = f'创建账号成功 用户名:{username} 密码:{password}'if users.__contains__(username):info = f'用户名{username}已存在'else:users[username] = passwordwrite(users)isok = True    response = RESPONSE.copy()response['main']['response'] = int(isok)response['main']['info'] = infouseobj.send(pickle.dumps(response.copy()))return isokdef main(useobj, address):print(f'建立链接:{address}')while True:try:info = useobj.recv(HIGHSIZE)info = pickle.loads(info)headers = info['headers']if headers['api'] != API or headers['mode'] != 'request':breakif headers['function'] == 'login':if login(useobj, info['main']['username'], info['main']['password']):breakelif headers['function'] == 'create':create(useobj, info['main']['username'], info['main']['password'])else:breakexcept (ConnectionResetError, KeyError):breakprint(f'结束了链接:{address}')useobj.close()sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((HOST, DATAPORT))
sock.listen()
while True:user, addr = sock.accept()thread = Thread(target=main, args=(user, addr))thread.start()

server.py

import socket
from configs import *
from threading import Threaddef broadcast(info: bytes):for nikename, useobj in clients.items():try:useobj.send(info)except (ConnectionResetError, OSError):print(f'{nikename}不在线')def main(useobj, address):print(f'建立链接:{address}')nikename = useobj.recvfrom(HIGHSIZE)[0].decode(ENCODING)clients[nikename] = useobjprint(f'{nikename}进入聊天室')broadcast(f'{nikename}进入聊天室'.encode(ENCODING))while True:try:data = useobj.recvfrom(HIGHSIZE)[0]broadcast(data)except ConnectionResetError:broadcast(f'{nikename}退出聊天室'.encode(ENCODING))breakprint(f'退出链接:{address}')useobj.close()sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((HOST, SENDPORT))
clients = {}
sock.listen()
while True:user, addr = sock.accept()thread = Thread(target=main, args=(user, addr))thread.start()

客户端

cilpboard.py

import win32con
import win32clipboarddef gets():  # 获取win32clipboard.OpenClipboard()text = win32clipboard.GetClipboardData(win32con.CF_UNICODETEXT)win32clipboard.CloseClipboard()return textdef sets(string):  # 设为win32clipboard.OpenClipboard()win32clipboard.EmptyClipboard()win32clipboard.SetClipboardData(win32con.CF_UNICODETEXT, string)win32clipboard.CloseClipboard()

listening.py

import PySimpleGUI as sg
from configs import *
from speaker import speakdef main(text):sg.theme(THEMECOLOR)sg.SetGlobalIcon(ICONPATH)layout = [[sg.Text(f'听一听  {text}'), sg.Text('\t\t')],[sg.Submit('听', key='-listen-')]]window = sg.Window('朗读器', layout)    while True:event, values = window.read()if event in (None, ):breakelif event == '-listen-':speak(text)    window.close()

speaker.py

from aip import AipSpeech
from playsound import playsound
from configs import *def speak(text, lang='zh', ctp=1, vol=5, spd=5, pit=8, per=4):client = AipSpeech(APPID, APPKEY, SECRETKEY)result = client.synthesis(text, lang, ctp,{'vol': vol,'spd': spd,'pit': pit,'per': per,})    path = 'resources/sounds/speaker.mp3'if not isinstance(result, dict):with open(path, 'wb') as f:f.write(result)          playsound(path)else:print(result)

account.py

import PySimpleGUI as sg
import socket
import pickle
from configs import *
from sys import exit
from verification import VerificationCode
from tkinter.messagebox import showerror, showinfodef send(username, password, sock):request = REQUEST.copy()request['headers']['function'] = 'create'request['main']['username'] = usernamerequest['main']['password'] = passwordsock.sendto(pickle.dumps(request), (HOST, DATAPORT))response = sock.recv(HIGHSIZE)response = pickle.loads(response)if not (response['headers']['api'] == API andresponse['headers']['mode'] == 'response' andresponse['main']['cookie'] == COOKIE):showwarning('警告', '服务器不正常')exit(2)return response['main']['response'] == 1, response['main']['info']def main(sock):v = VerificationCode()right = v.getimage('captcha')    def reverifcation():nonlocal v, rightv = VerificationCode()right = v.getimage('captcha')    sg.theme(THEMECOLOR)sg.SetGlobalIcon(ICONPATH)layout = [[sg.Text('用户名:'), sg.InputText(key='-username-')],[sg.Text('密码:'), sg.InputText(key='-password1-', password_char='·')],[sg.Text('再次输入密码:'), sg.InputText(key='-password2-', password_char='·')],[sg.Text('验证码:'), sg.InputText(key='-captcha-'),sg.Image(CAPTCHA.replace('{name}', 'captcha'), key='-vcode-'),sg.Submit('切换', key='-rever-')],[sg.Quit('取消', key='-quit-'), sg.Submit('创建', key='-send-')]]window = sg.Window('注册账号', layout)login = Falseusername = ''while True:event, values = window.read(timeout=100)if event in (None, '-quit-'):breakelif event == '-send-':captcha = window.find_element('-captcha-').get()username = window.find_element('-username-').get()password1 = window.find_element('-password1-').get()password2 = window.find_element('-password2-').get()if captcha != right:showerror('提示', '验证码错误')continueif password1 != password2:showerror('提示', '密码不一致')continueif (username in ('', ' ')) or (password1 in ('', ' ')):showerror('提示', '用户名或密码不得为空')continueisok, info = send(username, password1, sock)if isok:showinfo('提示', info)login = Truebreakelse:showerror('提示', info)elif event == '-rever-':reverifcation()window.find_element('-vcode-').update(CAPTCHA.replace('{name}', 'captcha'))    window.close()return login, username

login.py

import PySimpleGUI as sg
import socket
import pickle
from sys import exit
from configs import *
from functions import read
from tkinter.messagebox import showerror, showinfo, askyesno, showwarning
from account import main as createsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, DATAPORT))def request(username, password):data = REQUEST.copy()data['main']['username'] = usernamedata['main']['password'] = passworddata['headers']['function'] = 'login'sock.sendto(pickle.dumps(data), (HOST, DATAPORT))try:response = sock.recv(HIGHSIZE)response = pickle.loads(response)if not (response['headers']['api'] == API andresponse['headers']['mode'] == 'response' andresponse['main']['cookie'] == COOKIE):showwarning('警告', '服务器不正常')exit(1)isok = response['main']['response'] == 1info = response['main']['info']return isok, infoexcept ConnectionResetError:showwarning('警告', '服务器不正常')exit(1)except KeyError:showwarning('警告', '服务器不正常')exit(1)def main():sg.theme(THEMECOLOR)sg.SetGlobalIcon(ICONPATH)creater = [['没有账号?', ['&new create一个']]]layout = [[sg.Menu(creater, tearoff=False, pad=(20, 1))],[sg.Text('用户名:'),sg.InputText(key='-username-')],[sg.Text('密码:'),sg.InputText(password_char='*', key='-password-')],[sg.Quit('退出', key='-exit-'), sg.Submit('登录', key='-submit-')],]    window = sg.Window(LOGINTITLE, layout)login = Falseusername = Nonewhile True:event, values = window.read(timeout=100)if event in (None, '-exit-'):if askyesno('提示', '确定退出?'):breakelif event == '-submit-':username = window.find_element('-username-').get()password = window.find_element('-password-').get()isok, info = request(username, password)if isok:showinfo('提示', info)login = Truebreakelse:showerror('提示', info)elif event == 'new create一个':login, username = create(sock)if login:breakwindow.close()return login, usernameif __name__ == '__main__':main()

verification.py

import string
import random
from PIL import Image, ImageDraw, ImageFont, ImageFilter
from configs import *class VerificationCode(object):def __init__(self):self.savepath = CAPTCHAdef getchar(self, length=4):chars = string.ascii_lowercase + string.digitsreturn ''.join(random.sample(chars, length)), lengthdef getcolor(self, low=50, high=150):return random.randint(low, high), \random.randint(low, high), \random.randint(low, high)def getimage(self, name, width=180, height=62, size=(60, 21)):image = Image.new('RGB', (width, height), self.getcolor(20, 100))font = ImageFont.truetype(CAPTCHAFONT, 40)pen = ImageDraw.Draw(image)char, length = self.getchar()        for i in range(length):pen.text((40 * i + 10, 0), char[i], font=font, fill=self.getcolor(100, 200))        for n in range(random.randint(200, 600)):x = random.randint(1, width - 1)y = random.randint(1, height - 1)pen.point((x, y), fill=self.getcolor())        image = image.filter(ImageFilter.BLUR)self.savepath = CAPTCHA.replace('{name}', name)image = image.resize(size, Image.ANTIALIAS)image.save(self.savepath)return char

client.py

import PySimpleGUI as sg
import socket
from threading import Thread
from configs import *
from speaker import speak
from sys import exit
from login import main as login
from cilpboard import gets, setsdef read():try:return sock.recvfrom(HIGHSIZE)[0].decode(ENCODING)except socket.timeout:return Nonedef write():window.find_element('-messages-').update(value)message = read()if message:value.append(message)sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.45)
sock.connect((HOST, SENDPORT))
islogin, nikename = login()
if not islogin:exit(1)
sock.send(nikename.encode(ENCODING))
sg.theme(THEMECOLOR)
sg.SetGlobalIcon(ICONPATH)
layout = [[sg.Listbox([], key='-messages-', size=(46, 28))],[sg.Text('输入发送信息:'),sg.InputText(size=(35, 5),right_click_menu=['&inputmenu',[' ', '&刷新', '&复制', '&粘贴', '&听语音']], key='-data-'),sg.Submit('发送', key='-send-')],[sg.Quit('退出', key='-exit-')]
]
window = sg.Window('飞鸽', layout)
value = ['欢迎来到飞鸽!', f'昵称:{nikename}']
window.read(timeout=1)
write()
while True:write()event, values = window.read()if event in (None, '-exit-'):breakelif event == '-send-':data = window.find_element('-data-').get()data = f'{nikename}: {data}'sock.send(data.encode(ENCODING))window.find_element('-data-').update('')elif event == '复制':sets(window.find_element('-data-').get())elif event == '粘贴':window.find_element('-data-').update(gets())elif event == '听语音':text = window.find_element('-data-').get()
window.close()

python+pysimplegui+socket开发登录聊天室相关推荐

  1. python 使用socket建立小型聊天室

    一个聊天室,由两个部分组成.服务端和客户端.服务端接收客户端发来的消息,并将接收到的消息发送给其他客户端.客户端负责发送消息到服务端,并接收来自服务端发送的来自其他客户端的消息. 示例图(服务端和客户 ...

  2. python socket 网络聊天室_Python基于Socket实现简单聊天室

    本文实例为大家分享了Python基于Socket实现简单聊天室,供大家参考,具体内容如下 服务端 #!/usr/bin/env python # -*- coding: utf-8 -*- # @Ti ...

  3. 基于Java socket的网络聊天室的设计与实现

    目 录 摘要 I Abstract II 目 录 III 1 引言 1 2 网络聊天室的简介 2 2.1网络聊天室现状和发展 2 3 完成网络聊天室的技术以及环境 4 3.1 Java的介绍 4 3. ...

  4. Java和WebSocket开发网页聊天室

    一.项目简介 WebSocket是HTML5一种新的协议,它实现了浏览器与服务器全双工通信,这里就将使用WebSocket来开发网页聊天室,前端框架会使用AmazeUI,后台使用Java,编辑器使用U ...

  5. FMS案例开发--视频聊天室(三)

    本文要介绍的内容主要有利用SharedObject来实现聊天文字聊天和在线用户的列表,以及实现语音视频聊天等. 前一篇文章介绍了实现用户注册和登录的功能,本文接着介绍用户注册并成功登录后的相关功能开发 ...

  6. Android基于XMPP Smack openfire 开发的聊天室

    公司刚好让做即时通讯模块,服务器使用openfire,偶然看到有位仁兄的帖子,拷贝过来细细研究,感谢此仁兄的无私,期待此仁兄的下次更新 转自http://blog.csdn.net/lnb333666 ...

  7. python简单的多人聊天室

    刚开始学习python,写了一个聊天室练练手. Server.py import socket,select,thread;host=socket.gethostname() port=5963 ad ...

  8. java socket编程聊天室_Java Socket通信之聊天室功能

    Java Socket通信之聊天室功能 发布时间:2020-10-17 14:36:00 来源:脚本之家 阅读:73 作者:LY_624 本文实例为大家分享了Java Socket聊天室功能的具体代码 ...

  9. 使用Socket实现通信聊天室

    使用Socket实现通信聊天室 通信聊天室是一个比较酷的项目. 建立通信聊天室之前我们会想到这些问题: ①聊天室得要有一个发送窗口和一个接受窗口,如何在这两个窗口建立联系? ②如何发送信息并且接受信息 ...

最新文章

  1. java 工厂模式的写法_[java设计模式] 工厂模式解析
  2. 如何在XAF中显示自定义窗体和控件
  3. wordpress 自定义删除后台管理菜单
  4. 非程序员如何使用 Git——版本控制你的生活
  5. JAVA的静态代理与动态代理比较--转载
  6. Serverless 工程实践 | 细数 Serverless 的配套服务
  7. chrome webdriver_(最新版)如何正确移除Selenium中的 window.navigator.webdriver
  8. [swift] LeetCode 234. Palindrome Linked List
  9. 交换机短路_交换机日常怎么运行维护?一文告诉你
  10. 使用ssl_exporter监控K8S集群证书
  11. 360再回应Citron财务造假 双方或将升到法律层面
  12. 读《About Face 4 交互设计精髓》9
  13. 树莓派4b-centos操作系统安装包
  14. Keil5下载烧录错误常见问题
  15. 服务实例是否宕机的后台检查线程任务
  16. windows 豆沙绿参数
  17. 实施不良资产证券化 信用评级不能少
  18. 一根均线选股法_一根均线选股法视频教程
  19. JS无限滚动、回到顶端和图片懒加载
  20. flex布局强制换行(flex-wrap:wrap)之后,去掉最下面一层多余的间隙。

热门文章

  1. 人物介绍的排版【小白进】
  2. HTML5游戏出现新转机
  3. python量化交易:Joinquant_量化交易基础【三】:python基本语法与变量
  4. 浙江大学计算机博士申请考核,考博经验|2020年浙江大学博士申请考核经验分享...
  5. JAVA制作弹出小广告的程序_微信小程序实现首页弹出广告
  6. 咕咕机vs喵喵机测评
  7. 同步异步,阻塞非阻塞,进程间通信
  8. 使用Celery 容联云 异步发送验证码详解!!!
  9. 主流蓝牙BLE控制芯片详解(1):TI CC2540
  10. Secure Boot什么意思?BIOS中Secure Boot灰色无法更改解决方法详解