圆月山庄资源网 Design By www.vgjia.com

本文实例为大家分享了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,聊天室

圆月山庄资源网 Design By www.vgjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
圆月山庄资源网 Design By www.vgjia.com

P70系列延期,华为新旗舰将在下月发布

3月20日消息,近期博主@数码闲聊站 透露,原定三月份发布的华为新旗舰P70系列延期发布,预计4月份上市。

而博主@定焦数码 爆料,华为的P70系列在定位上已经超过了Mate60,成为了重要的旗舰系列之一。它肩负着重返影像领域顶尖的使命。那么这次P70会带来哪些令人惊艳的创新呢?

根据目前爆料的消息来看,华为P70系列将推出三个版本,其中P70和P70 Pro采用了三角形的摄像头模组设计,而P70 Art则采用了与上一代P60 Art相似的不规则形状设计。这样的外观是否好看见仁见智,但辨识度绝对拉满。