Python socket实现简单聊天室

yipeiwu_com6年前Python基础

本文实例为大家分享了Python socket实现简单聊天室的具体代码,供大家参考,具体内容如下

服务端使用了select模块,实现了对多个socket的监控。客户端由于select在Windows下只能对socket使用,所以使用了多线程来实现对客户端输入和socket连接的同时监控。注意这里的socket设置为了非阻塞。这样就实现了在一个线程中同时进行socket的接收和发送。

服务器代码:

# -*- coding: utf-8 -*-
import socket,select

connection_list = []
host = ''
port = 10001

def board_cast(sock,message):
 for socket in connection_list:
  if socket != server_sock and socket != sock:
   try:
    socket.send(message)
   except:
    socket.close()
    print str(socket.getpeername())+' is offline'
    connection_list.remove(socket)

server_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
server_sock.setblocking(0)
server_sock.bind((host,port))
server_sock.listen(10)
connection_list.append(server_sock)

while 1:
 readable,writable,error = select.select(connection_list,[],[])
 for sock in readable:
  if sock == server_sock:
   connection,connection_add = sock.accept()
   message = str(connection_add)+'enter room'
   board_cast(connection,message)
   print connection_add,'%s connect'
   connection_list.append(connection)
  else:
   try:
    date = sock.recv(1024)
    print date
    board_cast(sock,'('+str(sock.getpeername())+') :'+date)
   except:
    message2 = str(sock.getpeername())+ 'is offline'
    board_cast(sock,message2)
    print str(sock.getpeername())+ ' is offline'
    sock.close()
    connection_list.remove(sock)
    continue

客户端代码:

# -*- coding: utf-8 -*-
import socket,threading,time
flag = 0
date = ''
lock = threading.Lock()

host = 'localhost'
port = 10001
client_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client_sock.setblocking(0)

class Mythread1(threading.Thread):
 def __init__(self):
  threading.Thread.__init__(self)
 def run(self):
  global flag, date
  while 1:
   date = raw_input()
   if len(date):
    lock.acquire()
    flag = 1
    lock.release()

class Mythread2(threading.Thread):
 def __init__(self):
  threading.Thread.__init__(self)
 def run(self):
  global flag
  global date
  while 1:
   try:
    buf = client_sock.recv(1024)
    if len(buf):
     print buf
   except:
    pass
   if flag:
    try:
     client_sock.send(date)
    except socket.error, e:
     print e
    lock.acquire()
    flag = 0
    lock.release()



try:
 client_sock.connect((host,port))
 print"连接成功"
except socket.error,e:
 print e

t1 = Mythread1()
t2 = Mythread2()
t1.start()
t2.start()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python中import与from方法总结(推荐)

一、模块&包简介 模块:所谓模块就是一个.py文件,用来存放变量,方法的文件,便于在其他python文件中导入(通过import或from)。 包(package): 包是更大的组织单位...

Python求解正态分布置信区间教程

Python求解正态分布置信区间教程

正态分布和置信区间 正态分布(Normal Distribution)又叫高斯分布,是一种非常重要的概率分布。其概率密度函数的数学表达如下: 置信区间是对该区间能包含未知参数的可置信的...

python3 自动识别usb连接状态,即对usb重连的判断方法

在做自动化测试时,遇到两种情况需要判断usb是否已连接上(注,本文仅针对用adb命令来control手机) 一种是在开测时(前提是同时要测试多台), 希望等待所有设备usb全部识别后同时...

python代码 if not x: 和 if x is not None: 和 if not x is None:使用介绍

代码中经常会有变量是否为None的判断,有三种主要的写法: 第一种是`if x is None`; 第二种是 `if not x:`; 第三种是`if not x is None`(这句...

Python模拟登陆淘宝并统计淘宝消费情况的代码实例分享

Python模拟登陆淘宝并统计淘宝消费情况的代码实例分享

支付宝十年账单上的数字有点吓人,但它统计的项目太多,只是想看看到底单纯在淘宝上支出了多少,于是写了段脚本,统计任意时间段淘宝订单的消费情况,看那结果其实在淘宝上我还是相当节约的说。 脚本...