只需五步,快速构建Python聊天室

Posted CSDN

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了只需五步,快速构建Python聊天室相关的知识,希望对你有一定的参考价值。

在本文中,我们来谈一谈如何构建一个Python聊天室。

注意:你不需要安装任何额外的Python包。

只需五步,快速构建Python聊天室


作者 |  Dark Soulz
译者 | 弯月,责编 | 郑丽媛
图 | CSDN 下载自东方 IC
出品 | CSDN(ID:CSDNnews)


只需五步,快速构建Python聊天室


只需五步,快速构建Python聊天室

概念介绍


大致来说,Python聊天室使用了套接字编程和多线程的概念。聊天室分为两个部分:服务器端程序socketserver.py和客户端程序chat.py。它支持聊天室或同时与多个用户连接的聊天框。但是,在进入下一阶段之前,我们先来学习套接字编程和多线程。如果不明白这两个概念,初学者很难理解下面构建的项目。

套接字编程

只需五步,快速构建Python聊天室

一般来说,你可以将套接字视为双向通信通道中的端点,帮助服务器和一个或多个客户端组加入通信。它允许客户端通过服务器与其他客户端交互。

多线程

只需五步,快速构建Python聊天室

多线程是一个子进程,可以负责运行其他任何线程中的各个命令。当用户连接到服务器时,就会创建一个新的线程,并根据为每个客户端的规范构建的套接字对象,通过单独的线程实现服务器到客户端的通信。


只需五步,快速构建Python聊天室

项目要求


● 一台拥有I5核心处理器的优质PC,负责运行各种程序。

● 一个用来写注释的记事本。

● 一个IDE,通常是VS Code Editor、Atom或Sublime。

● 最重要的是,你必须在PC上安装Python才能执行任何Python程序。

● 专注。


只需五步,快速构建Python聊天室

如何构建Python聊天室?


首先,在桌面上创建一个名为Python chatbox或chatroom的文件夹,用于保存所有的文件。

然后,将你的文件拖到IDE中,并创建两个文件,即chat.py (客户端脚本/GUI部分)和socketserver.py(服务器端脚本)。

注意:无需安装任何Python软件包,因为Python安装包自带所有的库。

第三,仔细阅读各个文件中的代码,并把这些代码放到你的文件中。

第四,首先执行Python socketserver.py,然后执行Python chat.py

第五,测试你的聊天框是否可以正常工作,然后这个DIY项目就完成了。


只需五步,快速构建Python聊天室

代码


socketserver.py

##Python codes to do server-side part of chat room.import _threadimport socketimport threading"""AF_INET is the address domain of the socket. This is used when we have an Internet Domain with any two hosts The 2nd context of the code is the type of socket. """s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)# piece of code to allow IP address & Porthost="127.0.0.1"port=5000s.bind((host,port))s.listen(5)clients=[]#code to allow users to send messagesdef connectNewClient(c): while True: global clients msg = c.recv(2048) msg ='Online ('+str(clients.index(c)+1)+'): '+msg.decode('ascii') sendToAll(msg,c)def sendToAll(msg,con): for client in clients: client.send(msg.encode('ascii'))  while True: c,ad=s.accept() # Display message when user connects print('*Server Connected ') clients.append(c) c.send(('Online ('+str(clients.index(c)+1)+')').encode('ascii')) _thread.start_new_thread(connectNewClient,(c,))

chat.py(GUI部分)

#Gui Programming Partimport tkinterimport socketimport _threadimport sys
# Code to create a new client socket and connect to the server
i = 3client = 0start = Truedef sendMessage (): msg = txt.get() client.send(msg.encode('ascii'))
def recievingMessage (c): global i while True : msg=c.recv(2048).decode('ascii') if not msg : sys.exit(0) global start if (start) : start = False #tkinter codes starts window.title(msg) continue msglbl = tkinter.Label(window,text=msg) msglbl['font']=("Courier",10) msglbl['bg']='black' msglbl['fg']='#0aff43' msglbl['width']=50 msglbl.grid(columnspan=2,column=0,row=i,padx=5) i += 1#Socket Creationdef socketCreation (): c = socket.socket(socket.AF_INET, socket.SOCK_STREAM) c.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)#Local Host # import all functions /# everthing from chat.py file host = '127.0.0.1' port = 5000 c.connect((host,port)) global client client = c send['command'] = sendMessage _thread.start_new_thread(recievingMessage, (c,) )

#Creating a windowwindow = tkinter.Tk()window.title('Chatbox')window['bg']='#242424'
window['padx']=10window['pady']=10#Adding Elements#Entrytxt = tkinter.Entry(window)txt['width']=50txt['relief']=tkinter.GROOVEtxt['bg']='#f5f6f7'txt['fg']='red'txt['font']=("Courier",12)txt.grid(column=0,row=1,padx=5,pady=15)#Buttonsend = tkinter.Button(window,text="Send")send['relief']=tkinter.GROOVEsend['bg']='red'send['fg']='white'send['activebackground']='#404040'send['padx']=3send['font']=("Courier",10)send.grid(column=1,row=1,padx=5,pady=15)

_thread.start_new_thread(socketCreation, () )

window.mainloop()


只需五步,快速构建Python聊天室

总结


上述给出了主要代码,本文的讲解可以帮助你理解代码的工作方式。最后,请严格执行文本的步骤,以防止运行程序时发生不必要的麻烦。感谢您的阅读!

原文:https://thecodezine.com/5-easy-way-to-build-a-python-chat-room/

本文为 CSDN 翻译,转载请注明来源出处。


只需五步,快速构建Python聊天室

只需五步,快速构建Python聊天室

更多精彩推荐

          
            
            
          
Mate40 成麒麟绝唱,光刻机进厂即遭抵押,北斗指路能否解除“芯痛”?
只需五步,快速构建Python聊天室
点分享
点点赞
点在看

以上是关于只需五步,快速构建Python聊天室的主要内容,如果未能解决你的问题,请参考以下文章

卓越培训:只需五步,让你轻松学好Java!

简单的方法来分享/讨论/协作的代码片段?

vs2003:快速片段工具

Android Studio 主题及字体修改,只需五步

如何从一组中继容器中组合片段?

图算法 - 只需“五步” ,获取两节点间的所有路径(非递归方式)