Python聊天室程序(基础版)_python
程序员文章站
2022-04-09 07:53:34
...
这篇文章主要为大家详细介绍了Python聊天室程序的基础版,包含客户端和服务器端两部分,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了Python聊天室程序的具体代码,供大家参考,具体内容如下
客户端代码:
# Filename: socketClient.py import socket import sys import threading # Client GUI from tkinter import * import Pmw # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect the socket to the port where the server is listening server_address = ('localhost', 10000) print (sys.stderr, 'connecting to %s port %s' % server_address) sock.connect(server_address) root = Tk() # textDisplay textDisplay = Pmw.ScrolledText(root) textDisplay.pack(expand=1, padx=5, pady=5,side = LEFT) # textInput textInput = Pmw.ScrolledText(root) textInput.pack(expand=1, padx=5, pady=5,side = LEFT) # Send Button and its callback def sendMsg(event): message = socket.gethostname()+':'+ textInput.get() #print (sys.stderr, 'sending "%s"' % message) print(message) sock.sendall(message.encode()) textInput.clear() #data = sock.recv(100) #textDisplay.insert(END, data) #print (sys.stderr, 'received "%s"' % data) sendBtn = Button(root, text="Send") sendBtn.bind('<Button-1>', sendMsg) sendBtn.pack(side = LEFT) def receiveMsg(): while True: data = sock.recv(100) print (sys.stderr, 'client received "%s"' % data) textDisplay.insert(END, data) receiveThread = threading.Thread(name='waitForMSG', target=receiveMsg) receiveThread.start() root.mainloop()
服务器端代码:
# Filename: socketServer.py import socket import sys # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind the socket to the port server_address = ('localhost', 10000) print (sys.stderr, 'starting up on %s port %s' % server_address) sock.bind(server_address) # Listen for incoming connections sock.listen(1) while True: # Wait for a connection print (sys.stderr, 'waiting for a connection') connection, client_address = sock.accept() try: print (sys.stderr, 'connection from', client_address) # Receive the data in small chunks and retransmit it while True: data = connection.recv(16) print (sys.stderr, 'received "%s"' % data) if data: print (sys.stderr, 'sending data back to the client') connection.sendall(data) else: print (sys.stderr, 'no data from', client_address) break finally: # Clean up the connection connection.close()
相关推荐:
以上就是Python聊天室程序(基础版)_python的详细内容,更多请关注其它相关文章!
上一篇: php编辑器哪个好用吗
下一篇: win10声音图标有红叉怎么办
推荐阅读
-
Python基础教程之if判断,while循环,循环嵌套
-
python微信聊天机器人改进版(定时或触发抓取天气预报、励志语录等,向好友推送)
-
详解用python实现基本的学生管理系统(文件存储版)(python3)
-
python基础教程之lambda表达式使用方法
-
基于腾讯云服务器部署微信小程序后台服务(Python+Django)
-
Python实现过滤单个Android程序日志脚本分享
-
Python2.6版本中实现字典推导 PEP 274(Dict Comprehensions)
-
python执行等待程序直到第二天零点的方法
-
python基础教程之udp端口扫描
-
最基础的Python的socket编程入门教程