Python聊天室程序(基础版)

日期: 2019-12-16 22:43 浏览次数 :

本文实例陈诉了遵照进度内通讯的python闲聊室达成情势。分享给咱们供我们参照他事他说加以考察。具体如下:

本文实例为大家分享了Python闲聊室程序的切切实实代码,供大家参照他事他说加以考察,具体内容如下

本文实例为我们大饱眼福了Python socket达成简单闲谈室的切切实实代码,供我们参照他事他说加以侦查,具体内容如下

#!/usr/bin/env python
# Added by <ctang@redhat.com>
import sys
import os
from multiprocessing import connection
ADDR = ('', 9997)
AUTH_KEY = '12345'
class Server(object):
  def __init__(self, username):
    self.auth_key = AUTH_KEY
    self.addr = ADDR
    self.username = username
    self.listener = connection.Listener(self.addr, authkey=self.auth_key)
  def listen(self):
    while True:
      conn = self.listener.accept()
      while True:
        try:
          request = conn.recv()
          response = self.response(request)
          conn.send(response)
        except EOFError:
          break
      conn.close()
  def reply(self):
    message = raw_input("%s: " % self.username)
    return message
  def output_request(self, request):
    sys.stdout.write('%s says: %sn' % request)
  def response(self, request):
    self.output_request(request)
    response = (self.username, self.reply())
    return response
class Client(object):
  def __init__(self, username):
    self.auth_key = AUTH_KEY
    self.addr = ADDR
    self.username = username
    self.display_name = self.make_display_name(username)
  def make_display_name(self, username):
    return "%s: " % username
  def connect(self):
    self.conn = connection.Client(self.addr, authkey=self.auth_key)
    while True:
      message = raw_input(self.display_name)
      self.send(message)
      response = self.conn.recv()
      self.output_response(response) 
  def send(self, message):
    self.conn.send((self.username, message))
  def output_response(self, response):
    sys.stdout.write('%s says: %sn' % response)
def main():
  mode = sys.argv[1]
  if mode == 'server':
    username = raw_input("Your name please: ")
    server = Server(username)
    server.listen()
  elif mode == 'client':
    username = raw_input("Your name please: ")
    client = Client(username)
    client.connect()
if __name__ == '__main__':
  main()

顾客端代码:

服务端使用了select模块,完结了对多少个socket的监察。顾客端由于select在Windows下只可以对socket使用,所以使用了三十二线程来兑现对顾客端输入和socket连接的同期监察和控制。注意这里的socket设置为了非窒碍。那样就完成了在一个线程中何况打开socket的收纳和出殡和安葬。

企望本文所述对大家的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() 

服务器代码: