首頁 > web前端 > js教程 > Python聊天室程式(基礎版)_python

Python聊天室程式(基礎版)_python

不言
發布: 2018-04-02 16:01:03
原創
1394 人瀏覽過

這篇文章主要為大家詳細介紹了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(&#39;<Button-1>&#39;, sendMsg)  
sendBtn.pack(side = LEFT) 
 
def receiveMsg(): 
  while True: 
    data = sock.recv(100) 
    print (sys.stderr, &#39;client received "%s"&#39; % data) 
    textDisplay.insert(END, data) 
   
 
receiveThread = threading.Thread(name=&#39;waitForMSG&#39;, 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 = (&#39;localhost&#39;, 10000) 
print (sys.stderr, &#39;starting up on %s port %s&#39; % server_address) 
sock.bind(server_address) 
 
# Listen for incoming connections 
sock.listen(1) 
 
while True: 
  # Wait for a connection 
  print (sys.stderr, &#39;waiting for a connection&#39;) 
  connection, client_address = sock.accept() 
 
  try: 
    print (sys.stderr, &#39;connection from&#39;, client_address) 
 
    # Receive the data in small chunks and retransmit it 
    while True: 
      data = connection.recv(16) 
      print (sys.stderr, &#39;received "%s"&#39; % data) 
      if data: 
        print (sys.stderr, &#39;sending data back to the client&#39;) 
        connection.sendall(data) 
      else: 
        print (sys.stderr, &#39;no data from&#39;, client_address) 
        break 
  finally: 
    # Clean up the connection 
    connection.close()
登入後複製

相關推薦:

Python程式中的觀察者模式結構編寫

以上是Python聊天室程式(基礎版)_python的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板