完成客户端进程的通信,还没解决登录成功后关闭面板的问题,或许可以返回一个什么作为客户端面版的命名

This commit is contained in:
lsy2246 2024-04-17 01:01:17 +08:00
parent 26922f4fe9
commit 783bc58482
12 changed files with 193 additions and 250 deletions

View File

@ -1,18 +1,22 @@
import json import json
import multiprocessing import multiprocessing
import os
import wx import wx
import threading import threading
import time import time
from Client.Process_session.Process_Client import ProcessClient
from .Chat_main import ChatFrame
class LoginFrame(wx.Frame): class LoginFrame(wx.Frame, ProcessClient):
def __init__(self): def __init__(self):
wx.Frame.__init__(self, None, id=1001, title='登录', pos=wx.DefaultPosition, size=(380, 300)) wx.Frame.__init__(self, None, id=-1, title='登录', pos=wx.DefaultPosition, size=(380, 300))
self.queue_in = multiprocessing.Queue() ProcessClient.__init__(self)
self.queue_out = multiprocessing.Queue()
self.queue_thread = threading.Thread(target=self.queue_recv) current_file_path = __file__
self.queue_thread.start() current_file_name = os.path.basename(current_file_path).split('.')[0]
self.Process_client_send("Server", "Name", current_file_name)
# 创建菜单栏 # 创建菜单栏
menu_bar = wx.MenuBar() menu_bar = wx.MenuBar()
@ -99,7 +103,10 @@ class LoginFrame(wx.Frame):
if receive_content["genre"] == '登录': if receive_content["genre"] == '登录':
match receive_content["data"]: match receive_content["data"]:
case 0: case 0:
# 关闭当前框架 app = wx.App()
frame = ChatFrame()
frame.Show()
app.MainLoop()
self.Close() self.Close()
case -1: case -1:
wx.MessageBox('重复登录', '登录', wx.OK | wx.ICON_INFORMATION) wx.MessageBox('重复登录', '登录', wx.OK | wx.ICON_INFORMATION)
@ -112,26 +119,6 @@ class LoginFrame(wx.Frame):
f'注册成功\n网名 : {receive_content["data"]['NetName']} \n账号 : {receive_content["data"]['Id']} \n密码 : {receive_content["data"]['Password']}', f'注册成功\n网名 : {receive_content["data"]['NetName']} \n账号 : {receive_content["data"]['Id']} \n密码 : {receive_content["data"]['Password']}',
'注册', wx.OK | wx.ICON_INFORMATION) '注册', wx.OK | wx.ICON_INFORMATION)
def queue_send(self, function, content):
data = json.dumps({"function": function, "content": content})
self.queue_out.put(data)
def queue_recv(self):
while True:
try:
data_json = self.queue_in.get()
data = json.loads(data_json)
self.queue_pick(data)
except Exception as e:
print("Error in queue_recv:", e)
def queue_pick(self, data):
match data["function"]:
case "server_status":
self.server_status = data["content"]
case "login_page_receive":
self.login_page_receive(data["content"])
def send_login_button(self, event): def send_login_button(self, event):
if self.server_status: if self.server_status:
account = self.login_panel.LoginPanel_account_text.GetValue().strip() account = self.login_panel.LoginPanel_account_text.GetValue().strip()
@ -140,7 +127,7 @@ class LoginFrame(wx.Frame):
target = "服务器" target = "服务器"
genre = "登录" genre = "登录"
data = {"genre": genre, "target": target, "content": content} data = {"genre": genre, "target": target, "content": content}
self.queue_send("send_server", data) self.Process_client_send("Session_server", "send_server", data)
def send_register_button(self, event): def send_register_button(self, event):
if self.server_status: if self.server_status:
@ -150,7 +137,15 @@ class LoginFrame(wx.Frame):
target = "服务器" target = "服务器"
genre = "注册" genre = "注册"
data = {"genre": genre, "target": target, "content": content} data = {"genre": genre, "target": target, "content": content}
self.queue_send("send_server", data) self.Process_client_send("Session_server", "send_server", data)
def Process_client_pick(self, data):
if data['target'] in ['ALL', 'Login']:
match data['function']:
case 'server_status':
self.server_status = data['content']
case 'login_page_receive':
self.login_page_receive(data['content'])
class LoginPanel(wx.Panel): class LoginPanel(wx.Panel):

View File

@ -0,0 +1,2 @@
from .Chat_main import *
from .Login import *

View File

@ -0,0 +1,30 @@
import json
import threading
from multiprocessing.connection import Client
class ProcessClient:
def __init__(self):
self.Process_port = 12321
self.Process_server = 'localhost'
self.Process_client_Client = Client((self.Process_server, self.Process_port))
Process_client_recv = threading.Thread(target=self.Process_client_recv)
Process_client_recv.start()
def Process_client_send(self, target, function, content):
data = {"target": target, "function": function, "content": content}
data_json = json.dumps(data)
self.Process_client_Client.send(data_json)
def Process_client_recv(self):
while True:
try:
data_json = self.Process_client_Client.recv()
data = json.loads(data_json)
self.Process_client_pick(data)
except EOFError:
print("连接已关闭")
break
def Process_client_pick(self, data):
pass

View File

@ -0,0 +1,46 @@
import json
import multiprocessing
from multiprocessing.connection import Listener
import threading
class ProcessServer:
def __init__(self):
self.Process_port = 12321
self.Process_server = 'localhost'
self.Process_server_listener = Listener((self.Process_server, self.Process_port))
self.Process_client_link_dick = {}
Process_client_link_Thread = threading.Thread(target=self.Process_client_link)
Process_client_link_Thread.start()
def Process_client_link(self):
while True:
client_connect = self.Process_server_listener.accept()
client_Thread_recv = threading.Thread(target=self.Process_client_recv, args=(client_connect,))
client_Thread_recv.start()
def Process_client_recv(self, client_Thread_recv):
while True:
data_json = client_Thread_recv.recv()
data = json.loads(data_json)
if data['target'] == 'Server':
if data['function'] == 'Name':
self.Process_client_link_dick[data['content']] = client_Thread_recv
else:
self.Process_client_pick(data)
def Process_client_send(self, target, function, content):
connect = self.Process_client_link_dick[target]
data = {"target": target, "function": function, "content": content}
data_json = json.dumps(data)
connect.send(data_json)
def Process_client_pick(self, data):
if data['target'] == 'ALL':
for value in self.Process_client_link_dick.values():
data_json = json.dumps(data)
value.send(data_json)
else:
if data['target'] in self.Process_client_link_dick.keys():
data_json = json.dumps(data)
self.Process_client_link_dick[data['target']].send(data_json)

View File

@ -0,0 +1,2 @@
from .Process_Server import *
from .Process_Client import *

View File

@ -1,50 +1,26 @@
import multiprocessing import multiprocessing
import os
import time import time
import socket import socket
import json import json
import threading import threading
from Client.Process_session.Process_Client import ProcessClient
class Session_server: class Session_server(ProcessClient):
def __init__(self): def __init__(self):
ProcessClient.__init__(self)
self.socker_ip = "127.0.0.1" self.socker_ip = "127.0.0.1"
self.socker_port = 8000 self.socker_port = 8000
self.server_socket = None self.server_socket = None
self.server_status = False # 服务器状态 self.server_status = False # 服务器状态
self.queue_in = multiprocessing.Queue()
self.queue_out = multiprocessing.Queue()
self.queue_thread = threading.Thread(target=self.queue_recv)
self.queue_thread.start()
self.link_server_Thread = threading.Thread(target=self.link_server) self.link_server_Thread = threading.Thread(target=self.link_server)
self.link_server_Thread.start() self.link_server_Thread.start()
self.receive_server_Thread = threading.Thread(target=self.receive_server) self.receive_server_Thread = threading.Thread(target=self.receive_server)
def queue_send(self, function, content): current_file_path = __file__
data = json.dumps({"function": function, "content": content}) current_file_name = os.path.basename(current_file_path).split('.')[0]
self.queue_out.put(data) self.Process_client_send("Server", "Name", current_file_name)
print(data)
def queue_recv(self):
while True:
try:
data_json = self.queue_in.get()
data = json.loads(data_json)
self.queue_pick(data)
except Exception as e:
print("Error in queue_recv:", e)
def queue_pick(self, data):
match data["function"]:
case "server_status":
self.server_status = data["content"]
case "send_server":
genre = data["content"]["genre"]
target = data["content"]["target"]
content = data["content"]["content"]
self.send_server(genre, target, content)
def link_server(self): def link_server(self):
while True: while True:
@ -62,7 +38,8 @@ class Session_server:
self.server_status = False self.server_status = False
print("连接错误:" + str(a)) print("连接错误:" + str(a))
finally: finally:
self.queue_send("server_status", self.server_status) self.Process_client_send("ALL", "server_status", self.server_status)
pass
def receive_server(self): def receive_server(self):
while self.server_status: while self.server_status:
@ -70,12 +47,11 @@ class Session_server:
receive_content_json = self.server_socket.recv(1024).decode('utf-8') receive_content_json = self.server_socket.recv(1024).decode('utf-8')
receive_content = json.loads(receive_content_json) receive_content = json.loads(receive_content_json)
if receive_content["genre"] in ['注册', '登录']: if receive_content["genre"] in ['注册', '登录']:
self.queue_send("login_page_receive", receive_content) self.Process_client_send("Login", "login_page_receive", receive_content)
print(receive_content)
except Exception as a: except Exception as a:
print("接收错误:" + str(a)) print("接收错误:" + str(a))
self.server_status = False self.server_status = False
self.queue_send("server_status", self.server_status) self.Process_client_send("ALL", "server_status", self.server_status)
def send_server(self, genre, target, content): def send_server(self, genre, target, content):
if self.server_status: if self.server_status:
@ -87,4 +63,13 @@ class Session_server:
except Exception as a: except Exception as a:
print("发送错误:" + str(a)) print("发送错误:" + str(a))
self.server_status = False self.server_status = False
self.queue_send("server_status", self.server_status) self.Process_client_send("ALL", "server_status", self.server_status)
def Process_client_pick(self, data):
if data['target'] in ['ALL', 'Session_server']:
match data['function']:
case 'server_status':
self.server_status = data['content']
print(self.server_status)
case 'send_server':
self.send_server(data['content']['genre'], data['content']['target'], data['content']['content'])

View File

@ -0,0 +1 @@
from .Session_server import *

View File

@ -1,14 +1,15 @@
from .Login import * from .Page import *
from .Session_server import * from .Socket_session import *
from .Chat_main import * from .Process_session import *
class start_all: class start_all:
def __init__(self): def __init__(self):
ProcessServer()
Session_server() Session_server()
app = wx.App(False) app = wx.App()
frame = LoginFrame() frame = LoginFrame()
frame.Show(True) frame.Show()
app.MainLoop() app.MainLoop()

View File

@ -1,151 +1,37 @@
import wx import json
import wx.aui import multiprocessing
import wx.lib.scrolledpanel as scrolled from multiprocessing.connection import Listener
import time import threading
class ChatFrame(wx.Frame): class ProcessServer:
def __init__(self): def __init__(self):
super().__init__(None, size=(1000, 700)) self.Process_port = 12321
self.Process_server = 'localhost'
self.Process_server_listener = Listener((self.Process_server, self.Process_port))
self.Process_client_link_dick = {}
Process_client_link_Thread = threading.Thread(target=self.Process_client_link)
Process_client_link_Thread.start()
ChatMain_Panel = wx.Panel(self, style=wx.BORDER_SUNKEN) def Process_client_link(self):
ChatMain_box = wx.BoxSizer(wx.HORIZONTAL) while True:
ChatMain_Panel.SetSizer(ChatMain_box) client_connect = self.Process_server_listener.accept()
print(type(client_connect))
Function_Panel = wx.Panel(ChatMain_Panel, style=wx.BORDER_RAISED) client_process_recv = threading.Thread(target=self.Process_client_recv, args=(client_connect,))
Function_box = wx.BoxSizer(wx.VERTICAL) client_process_recv.start()
Function_Panel.SetSizer(Function_box)
Function_Panel.SetBackgroundColour(wx.Colour(242, 242, 242))
image_chat = r'./Client/image/chat.png' def Process_client_recv(self, client_process_recv):
Chat_bitmap = wx.Bitmap(image_chat, wx.BITMAP_TYPE_PNG) while True:
Chat_bitmap_static = wx.StaticBitmap(Function_Panel, bitmap=Chat_bitmap, style=wx.BORDER_RAISED) data_json = client_process_recv.recv()
Chat_bitmap_static.SetToolTip("聊天") data = json.loads(data_json)
Function_box.Add(Chat_bitmap_static, 1, wx.EXPAND, 0) print(data)
Chat_bitmap_static.Bind(wx.EVT_LEFT_DOWN, self.click_chat_button)
Function_box.AddSpacer(30) # 调整这个数字以改变间距大小 def Process_client_send(self, target, function, content):
connect = self.Process_client_link_dick[target]
data = {"target": target, "function": function, "content": content}
data_json = json.dumps(data)
connect.send(data_json)
image_connect = r'./Client/image/connect.png' def Process_client_pick(self):
connect_bitmap = wx.Bitmap(image_connect, wx.BITMAP_TYPE_PNG) pass
connect_bitmap_static = wx.StaticBitmap(Function_Panel, bitmap=connect_bitmap, style=wx.BORDER_RAISED)
connect_bitmap_static.SetToolTip("通讯录")
Function_box.Add(connect_bitmap_static, 1, wx.EXPAND, 0)
connect_bitmap_static.Bind(wx.EVT_LEFT_DOWN, self.click_connect_button)
Function_box.AddSpacer(28) # 调整这个数字以改变间距大小
image_find = r'./Client/image/find.png'
find_bitmap = wx.Bitmap(image_find, wx.BITMAP_TYPE_PNG)
find_bitmap_static = wx.StaticBitmap(Function_Panel, bitmap=find_bitmap, style=wx.BORDER_RAISED)
find_bitmap_static.SetToolTip("查找")
Function_box.Add(find_bitmap_static, 1, wx.EXPAND, 0)
find_bitmap_static.Bind(wx.EVT_LEFT_DOWN, self.click_find_button)
Function_box.AddSpacer(340) # 调整这个数字以改变间距大小
image_site = r'./Client/image/site.png'
site_bitmap = wx.Bitmap(image_site, wx.BITMAP_TYPE_PNG)
site_bitmap_static = wx.StaticBitmap(Function_Panel, bitmap=site_bitmap, style=wx.BORDER_RAISED)
site_bitmap_static.SetToolTip("设置")
Function_box.Add(site_bitmap_static, 1, wx.EXPAND, 0)
site_bitmap_static.Bind(wx.EVT_LEFT_DOWN, self.click_site_button)
Function_box.Fit(Function_Panel) # 调整面板大小以适应图像
ChatMain_box.Add(Function_Panel, 0, wx.EXPAND | wx.ALL, 5)
operate_box = wx.BoxSizer(wx.VERTICAL)
chat_page = self.ChatPage(ChatMain_Panel) # 将 ChatMain_Panel 作为 ChatPage 的 parent
operate_box.Add(chat_page, 1, wx.EXPAND, 5)
ChatMain_box.Add(operate_box, 1, wx.EXPAND, 5)
ChatMain_Panel.SetSizer(ChatMain_box)
def click_chat_button(self, event):
print("点击了聊天")
def click_connect_button(self, event):
print("点击了联系人")
def click_site_button(self, event):
print("点击了设置")
def click_find_button(self, event):
print("点击了查找")
class ChatPage(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent, style=wx.BORDER_SUNKEN)
ChatPage_main_box = wx.BoxSizer(wx.HORIZONTAL)
self.ChatPage_add_Contact_text_box_dick = {}
ChatPage_Contact_person_box = wx.BoxSizer(wx.VERTICAL)
self.ChatPage_Contact_person_panel = scrolled.ScrolledPanel(self, -1, style=wx.SUNKEN_BORDER)
self.ChatPage_Contact_person_panel.SetupScrolling() # 启用滚动功能
self.ChatPage_Contact_person_panel.SetSizer(wx.BoxSizer(wx.VERTICAL))
ChatPage_Contact_person_box.Add(self.ChatPage_Contact_person_panel, proportion=1, flag=wx.EXPAND | wx.ALL,
border=5)
ChatPage_main_box.Add(ChatPage_Contact_person_box, 1, wx.EXPAND, 5)
self.ChatPage_add_Contact_person(11, "lsy", "asdasddsa")
self.chat_tab = wx.aui.AuiNotebook(self,style=wx.aui.AUI_NB_CLOSE_ON_ALL_TABS)
ChatPage_main_box.Add(self.chat_tab, 1, wx.EXPAND, 0)
self.SetSizer(ChatPage_main_box)
def ChatPage_add_Contact_person(self, Id, Remark, info):
ChatPage_add_Contact_person_box = wx.BoxSizer(wx.VERTICAL)
ChatPage_add_Contact_person_top_box = wx.BoxSizer(wx.HORIZONTAL)
if len(Remark) > 6:
Remark = Remark[:6] + "..."
else:
Remark += ''.join([" " for i in range(max(0, 9 - len(Remark)))])
ChatPage_add_Contact_person_NetName = wx.StaticText(self.ChatPage_Contact_person_panel, -1, Remark)
ChatPage_add_Contact_person_top_box.Add(ChatPage_add_Contact_person_NetName, 0, wx.ALIGN_LEFT, 0)
ChatPage_add_Contact_person_top_box.AddSpacer(20)
ChatPage_add_Contact_person_date = wx.StaticText(self.ChatPage_Contact_person_panel, -1,
time.strftime("%Y/%m/%d", time.localtime()))
ChatPage_add_Contact_person_top_box.Add(ChatPage_add_Contact_person_date, 0, wx.ALIGN_CENTER_VERTICAL, 0)
ChatPage_add_Contact_person_box.Add(ChatPage_add_Contact_person_top_box, 0, wx.EXPAND, 0)
if len(info) > 10:
info = info[:10] + "..."
ChatPage_add_Contact_person_info = wx.StaticText(self.ChatPage_Contact_person_panel, -1, info)
ChatPage_add_Contact_person_box.Add(ChatPage_add_Contact_person_info, 0, wx.ALIGN_LEFT, 0)
self.ChatPage_Contact_person_panel.GetSizer().Add(ChatPage_add_Contact_person_box, 0, wx.ALL, 5)
self.ChatPage_Contact_person_panel.Layout()
self.ChatPage_Contact_person_panel.SetupScrolling()
ChatPage_add_Contact_person_NetName.Bind(wx.EVT_LEFT_DOWN, lambda event: self.ChatPage_add_Contact_tab(Id, Remark))
def ChatPage_add_Contact_tab(self, Id, Remark):
for i in range(self.chat_tab.GetPageCount()):
if self.chat_tab.GetPageText(i) == Remark:
return
chat_panel = wx.Panel(self.chat_tab)
chat_box = wx.BoxSizer(wx.VERTICAL)
chat_receive_box = wx.BoxSizer(wx.HORIZONTAL)
chat_receive_text = wx.TextCtrl(chat_panel, style=wx.TE_MULTILINE)
chat_receive_box.Add(chat_receive_text, 0, wx.EXPAND, 0)
chat_box.Add(chat_receive_box, 1, wx.EXPAND, 0)
self.chat_tab.AddPage(chat_panel, wx.Panel(), Remark, select=True) # 将第三个参数改为 wx.Panel(),表示每个页面使用一个新的 Panel 承载控件
chat_panel.SetSizer(chat_box)
app = wx.App()
frame = ChatFrame()
frame.Show()
app.MainLoop()

View File

@ -1,43 +1,38 @@
# 客户端 import json
import socket import threading
import cv2 from multiprocessing.connection import Client
import pickle
import struct
HOST = '127.0.0.1' # 服务器IP地址
PORT = 65432 # 连接端口
# 创建Socket class ProcessClient:
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def __init__(self):
client_socket.connect((HOST, PORT)) self.Process_port = 12321
self.Process_server = 'localhost'
self.Process_client_Client = Client((self.Process_server, self.Process_port))
Process_client_recv = threading.Thread(target=self.Process_client_recv)
print(self.Process_client_Client)
Process_client_recv.start()
# 接收数据 def Process_client_send(self, target, function, content):
data = b"" data = {"target": target, "function": function, "content": content}
payload_size = struct.calcsize("Q") data_json = json.dumps(data)
while True: self.Process_client_Client.send(data_json)
# 从服务器接收数据
while len(data) < payload_size:
packet = client_socket.recv(4*10240)
if not packet: break
data += packet
packed_msg_size = data[:payload_size]
data = data[payload_size:]
msg_size = struct.unpack("Q", packed_msg_size)[0]
# 接收视频帧 def Process_client_recv(self):
while len(data) < msg_size: while True:
data += client_socket.recv(4*1024) try:
frame_data = data[:msg_size] data_json = self.Process_client_Client.recv()
data = data[msg_size:] data = json.loads(data_json)
print(data)
except EOFError:
print("连接已关闭")
break
# 反序列化视频帧 def Process_client_pick(self):
frame = pickle.loads(frame_data) pass
# 显示视频
cv2.imshow('frame', frame)
if cv2.waitKey(1) == 27:
break
# 释放资源 if __name__ == '__main__':
client_socket.close() xx = ProcessClient()
cv2.destroyAllWindows() while True:
a = input("请输入")
xx.Process_client_send(a, a, a)

View File

@ -1,5 +1,5 @@
import wx import wx
from Client.Chat_main import ChatFrame from Client.Page.Chat_main import ChatFrame
if __name__ == '__main__': if __name__ == '__main__':
app = wx.App() app = wx.App()