socket多线程通讯实例分析,基于进程内通讯的python聊天室实现方法
分类:多线程

传说进度内通信的python闲话室达成情势,python闲聊室

正文实例陈说了基于进度内通信的python闲谈室完成格局。分享给大家供大家参照他事他说加以考查。具体如下:

#!/usr/bin/env python
# Added by <[email protected]>
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()

瞩望本文所述对我们的Python程序设计有着援助。

本文实例陈诉了基于进度内通信的python闲聊室达成情势。分享给大家供我们参谋。具体...

正文实例叙述了基于进度内通讯的python闲话室完毕格局。分享给我们供大家参谋。具体如下:

python socket多线程通信实例深入分析(闲聊室卡塔尔,pythonsocket

本文实例陈述了python socket三十二线程通信情势。分享给我们供大家参谋,具体如下:

#!/usr/bin/evn python
"""
这是一个Socket+多进程的例子(聊天服务端)
"""
import socket
import threading
# 处理中文数据用的
encoding = "GBK"
def HKServer(client, addr):
 """
 与客户端时实通讯函数
 加入encoding是为了处理输入中文数据
 client 客户socket
 addr  客户address
 """
 # 通知已有的每个客户,有新的成员加入
 for c in clients: c.send(bytes("[%s]加入rn" % addr[1], encoding))
 # 接受客户端数据
 say = b""
 while True:
  data = client.recv(1024)
  if not data: break
  # 如果不是回车键
  if data != b'rn':
   say += data #.encode(encoding)
   continue
  # 把客户端发来的内容发给所有的客户端
  for c in clients:
   c.send(bytes("[%s]:%srn" % (addr[1], say.decode(encoding)), encoding))
  # 内容归x0
  say = b""
 # 客户离开后,从客户列表中移队当前客户,关闭socket连接
 clients.remove(client)
 client.close()
 # 通知已有的每个客户,有成员离开
 for c in clients: c.send(bytes("[%s]离开rn" % addr[1], encoding))
# 客户端列表
clients = []
# 设置IP地址与端口
HOST = ''
PORT = 9999
# 初始化socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定IP地址与端口
s.bind((HOST, PORT))
# 开始监听
s.listen(1)
# 循环等待
while True:
 # 接受客户
 client, addr = s.accept()
 # 启动新的进程与客户通信
 thread = threading.Thread(target=HKServer, args=(client, addr))
 thread.start()
 # 记录新的客户
 clients.append(client)

盼望本文所述对大家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: %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()

你或然感兴趣的稿子:

  • Python三十二线程爬虫简单示例
  • Python完毕轻易七十四线程职分队列
  • Python 四十五十六线程抓取图片成效比较
  • Python四线程、异步+多进度爬虫实今世码
  • 尝试选取Python四线程抓取代理服务器IP地址的示范
  • 基python达成多线程网页爬虫
  • Python完毕多线程抓取妹子图
  • Python四线程结合队列下载百度音乐的方法
  • Python达成急忙多线程ping的办法
  • Python十六线程下载文件的诀窍
  • 用Python达成二个粗略的二十四线程TCP服务器的学科
  • 浅析Python多线程下的变量难点
  • Python3中八线程编制程序的行列运作示例
  • 精解Python Socket互联网编制程序
  • python通过socket查询whois的方法
  • python使用socket远程连接错误管理方法

socket十六线程通信实例深入分析(闲聊室卡塔尔(قطر‎,pythonsocket 本文实例陈说了python socket四线程通信方式。分享给大家供大家参考,具体如下: #!/usr...

客商端代码:

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

你大概感兴趣的篇章:

  • python编写简易闲谈室实现实形势域网内闲聊作用
  • Python Socket编制程序之四线程闲聊室
  • 听大人讲python完成闲聊室程序
  • Python实现基于C/S构造的闲聊室效能详细解释
  • Python闲聊室程序(底工版)
  • Python socket完成轻便聊天室
  • python基于twisted框架编写轻巧闲扯室
  • 眇小闲聊室Python代码落成
  • python socket三十二线程通信实例解析(闲聊室卡塔尔国
  • Python闲聊室实例程序分享
  • Python达成的接纳telnet登入聊天室实例
  • Python socket C/S构造的闲聊室应用实现
  • python实现多少人聊天室

 服务器端代码:

# 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编写简易闲聊室达成实时局域网内闲谈功效
  • Python Socket编制程序之多线程闲聊室
  • 基于python完成谈天室程序
  • Python落成基于C/S布局的聊天室功效安详严整
  • Python socket完毕轻易闲扯室
  • python基于twisted框架编写简单闲谈室
  • 小小的闲聊室Python代码达成
  • python socket多线程通信实例深入分析(闲谈室State of Qatar
  • Python闲谈室实例程序分享
  • 据说进度内通信的python闲聊室完毕方式
  • Python完毕的利用telnet登录闲聊室实例
  • Python socket C/S构造的闲谈室应用达成
  • python达成几个人谈心室

本文由10bet手机官网发布于多线程,转载请注明出处:socket多线程通讯实例分析,基于进程内通讯的python聊天室实现方法

上一篇:安装星际译王 下一篇:HTML基础语句
猜你喜欢
热门排行
精彩图文