首页 编程教程正文

基于进程内通讯的python聊天室实现方法

piaodoo 编程教程 2020-02-02 12:26:59 1003 0 python教程

这篇文章主要介绍了基于进程内通讯的python聊天室实现方法,实例分析了Python聊天室的相关实现技巧,需要的朋友可以参考下

本文实例讲述了基于进程内通讯的python聊天室实现方法。分享给大家供大家参考。具体如下:

#!/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: %s\n' % 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: %s\n' % 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()

希望本文所述对大家的Python程序设计有所帮助。

版权声明:

本站所有资源均为站长或网友整理自互联网或站长购买自互联网,站长无法分辨资源版权出自何处,所以不承担任何版权以及其他问题带来的法律责任,如有侵权或者其他问题请联系站长删除!站长QQ754403226 谢谢。

有关影视版权:本站只供百度云网盘资源,版权均属于影片公司所有,请在下载后24小时删除,切勿用于商业用途。本站所有资源信息均从互联网搜索而来,本站不对显示的内容承担责任,如您认为本站页面信息侵犯了您的权益,请附上版权证明邮件告知【754403226@qq.com】,在收到邮件后72小时内删除。本文链接:https://www.piaodoo.com/1670.html

搜索