首页 >web前端 >js教程 >Python聊天室程序(基础版)_python

Python聊天室程序(基础版)_python

不言
不言原创
2018-04-02 16:01:031380浏览

这篇文章主要为大家详细介绍了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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn