服務端
實作目標
- GUI顯示人機互動聊天內容,當客戶端輸入不完整內容,如’how old’,服務器能回復年齡等,
- GUI當客戶端輸入“send a file”,服務器端回復“please input the file name:”(在客戶端顯示),
- (此處本文章代碼未實作,需要請聯系博主)當客戶端輸入檔案名后,服務器端如果有該檔案,則發送該檔案,否則回復客戶端“This file does not exist”,客戶端列印接收到的檔案內容,
- (選)實作服務器與多客服通信功能,(若需要,請聯系博主)
- 博主郵箱:3303295829@qq.com
聊天功能模糊實作原理
commonprefix()函式
- os.path.commonprefix()是Python中的方法用于獲取路徑串列中最長的公共路徑前綴,博主采用此函式來猜測對方要表達的真正意思,
實作代碼
# -*- coding: utf-8 -*-
"""
Created on 2021-12-21 下午 07:47
@author: 淺笑醉紅樓.(3303295829@qq.com)
@Software: PyCharm
(1) create by 淺笑醉紅樓. 2021-12-21 下午 07:47
"""
import socket
from os.path import commonprefix
words={'how are you?':'Fine,thank you.',
'how old are you?':'38',
'what is your name?':'DongFuGuo',
"what's your name?":'DongFuGuo',
'where do you work?':'SDIBT',
'bye':'Bye',
'send a file':'please input the file name:'}
HOST='' #IP地址
PORT=5007
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 系結scoket
s.bind((HOST,PORT))
# 開始監聽
s.listen(1)
print('Listening at port:',PORT)
conn,addr=s.accept()
print('Connected by',addr)
while True:
data = conn.recv(1024).decode()
if not data:
break
print('Received message:', data)
m = 0
key = ''
for k in words.keys():
data = ' '.join(data.split())
if len(commonprefix([k, data])) > len(k)*0.7:
key = k
break
length = len(set(data.split())&set(k.split()))
if length > m:
m = length
key = k
conn.sendall(words.get(key, 'Sorry.').encode())
conn.close()
s.close()
客服端
- GUI登錄端代碼見Python的GUI程式設計
- 實作代碼如下:
# -*- coding: utf-8 -*-
"""
Created on 2021-12-22 上午 10:54
@author: 淺笑醉紅樓.(3303295829@qq.com)
@Software: PyCharm
(1) create by 淺笑醉紅樓. 2021-12-22 上午 10:54
"""
import wx
import socket
import sys
import struct
class ChatWND(wx.Frame):
def __init__(self, superior):
wx.Frame.__init__(self, parent=superior,title=u'Chat Window', size=(800, 600))
self.panel = wx.Panel(self, wx.ID_ANY)
self.panel.SetBackgroundColour("Green")
self.label1 = wx.StaticText(self.panel, -1, 'IP:', style=wx.ALIGN_LEFT)
self.label2 = wx.StaticText(self.panel, -1, 'PORT:', style=wx.ALIGN_RIGHT)
self.label3 = wx.StaticText(self.panel, -1, 'MSG:', style=wx.ALIGN_LEFT, size=(50, 50))
self.label4 = wx.StaticText(self.panel, -1, 'Send:', style=wx.ALIGN_LEFT, size=(50, 50))
self.textIP = wx.TextCtrl(self.panel, -1)
self.textPORT = wx.TextCtrl(self.panel, -1)
self.textRecord = wx.TextCtrl(self.panel, -1, style=wx.TE_MULTILINE, size=(520, 200))
self.textSend = wx.TextCtrl(self.panel, -1, style=wx.TE_MULTILINE, size=(520, 30))
self.buttonConnectSvr = wx.Button(self.panel, -1, 'Connect')
self.buttonSendMsg = wx.Button(self.panel, -1, 'Send')
self.buttonGetFiles = wx.Button(self.panel, -1, 'File')
sizer1 = wx.FlexGridSizer(2, 2, 20, 15)
sizer1.AddMany(
[
(self.label3, 0, wx.ALIGN_LEFT),
(self.textRecord, 0, wx.ALIGN_RIGHT),
(self.label4, 0, wx.ALIGN_LEFT),
(self.textSend, 0, wx.ALIGN_RIGHT),
])
sizer2 = wx.FlexGridSizer(1, 7, 5, 5)
sizer2.AddMany(
[(self.label1, 0, wx.ALIGN_LEFT),
(self.textIP, 0, wx.EXPAND),
(self.label2, 0, wx.ALIGN_LEFT),
(self.textPORT, 0, wx.ALIGN_RIGHT),
(self.buttonConnectSvr, 0, wx.EXPAND),
(self.buttonSendMsg, 0, wx.EXPAND),
(self.buttonGetFiles, 0, wx.ALIGN_RIGHT)
])
self.border = wx.BoxSizer(wx.VERTICAL)
self.border.Add(sizer1, 0, wx.ALL, 15)
self.border.Add(sizer2, 0, wx.ALL, 15)
self.panel.SetSizerAndFit(self.border)
self.Fit()
self.Bind(wx.EVT_BUTTON, self.OnButtonConnectSvr,self.buttonConnectSvr)
self.Bind(wx.EVT_BUTTON, self.OnButtonSendMsg,self.buttonSendMsg)
self.Bind(wx.EVT_BUTTON, self.OnButtonGetFiles,self.buttonGetFiles)
def ConnectSvr(self, HOST, PORT):
# HOST->服務端主機IP地址
# PORT->服務端主機埠號
self.ClientSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
self.ClientSocket.connect((HOST, int(PORT))) # 連接服務器
print('連接至服務器')
except socket.error:
print('Server not found or not open')
sys.exit()
def OnButtonConnectSvr(self, event):
HOST = self.textIP.GetValue()
PORT = self.textPORT.GetValue()
self.ConnectSvr(HOST, PORT)
def Chat(self):
strMsg = self.strSend
self.ClientSocket.sendall(strMsg.encode()) # 發送資料
data = self.ClientSocket.recv(1024)
data = data.decode()
record = self.textRecord.GetValue() + 'Sever:' + data + '\n'
self.textRecord.SetValue(record)
if (strMsg.lower() == 'bye'):
self.ClientSocket.sendall(strMsg.encode())
data = self.ClientSocket.recv(1024)
record = self.textRecord.GetValue() + 'Sever:' + data + '\n'
self.textRecord.SetValue(record)
self.ClientSocket.close() # 關閉連接
def OnButtonSendMsg(self, event):
self.strSend = self.textSend.GetValue()
record = self.textRecord.GetValue() + 'Me:' + self.strSend + '\n'
self.textRecord.SetValue(record)
self.textSend.SetValue('')
self.Chat()
def GetFiles(self):
filename = self.strSend
self.ClientSocket.sendall(filename.encode())
data = self.ClientSocket.recv(1024)
if (data.decode() == 'This file does not exist'):
record = self.textRecord.GetValue() + 'Sever:' + data.decode() + '\n'
self.textRecord.SetValue(record)
else:
data = self.ClientSocket.recv(1024)
f_info = struct.unpack('l', data)
file_size = f_info[0]
recv_size = 0
with open(filename[:filename.rfind('.')] + '_new' +
filename[filename.rfind('.'):], 'wb') as fp:
while not recv_size == file_size:
if file_size - recv_size > 1024:
data = self.ClientSocket.recv(1024)
recv_size += len(data)
else:
data = self.ClientSocket.recv(file_size - recv_size)
recv_size = file_size
fp.write(data)
record = self.textRecord.GetValue() + 'Received a file' + '\n'
self.textRecord.SetValue(record)
def OnButtonGetFiles(self, event):
self.strSend = self.textSend.GetValue()
record = self.textRecord.GetValue() + 'Me:' + self.strSend + '\n'
self.textRecord.SetValue(record)
self.textSend.SetValue('')
self.GetFiles()
if __name__ == '__main__':
app=wx.App()
frame = ChatWND(None)
frame.Show()
app.MainLoop()

最后,大家懂得都懂,代碼可以拿走,請把贊留下
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/391430.html
標籤:其他
上一篇:VLAN虛擬局域網
