参考来源(其实我从上面复制了一点):
Python 的 Socket 编程教程  http://www.oschina.net/question/12_76126
Python线程指南 http://www.open-open.com/lib/view/open1345476194313.html
Python Socket文档 https://docs.python.org/3/library/socket.html#socket-objects

具体思路:
每个client有两个线程,分别负责接收和发送,当没有发送时,在raw_input()那卡住,当没有接收时,在recv()那卡住
server为每个client开两个线程,分别处理接收和发送。每个发送的线程在con.wait()那阻塞,等待notify。每个接收的线程,在recv()那里等待来自client的输入,接收到输入后,发出一个notify,激活所有输出线程,自身则因为循环在下一个recv()那里等待。

这样做的优势时在等待期间,cpu都处于空闲状态,cpu只在接收和发送的瞬间被使用。
目前没有想到更好方法。。。

注意:
我做得有点粗糙,复制后有些注释和代码对应不起来,也没有添加新的注释

 
标签: <无>
 

代码片段(4)[全屏查看所有代码]

1. [文件] client.py ~ 976B     下载(283)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 24 17:35:50 2013
 
@author: zbg
"""
 
import socket
import threading
 
 
inString = ''
outString = ''
nick = ''
 
def DealOut(s):
    global nick, outString
    while True:
        outString = raw_input()
        outString = nick + ': ' + outString
        s.send(outString)
 
def DealIn(s):
    global inString
    while True:
        try:
            inString = s.recv(1024)
            if not inString:
                break
            if outString != inString:
                print inString
        except:
            break
         
 
nick = raw_input("input your nickname: ")
ip = raw_input("input the server's ip adrress: ")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((ip, 8888))
sock.send(nick)
 
thin = threading.Thread(target = DealIn, args = (sock,))
thin.start()
thout = threading.Thread(target = DealOut, args = (sock,))
thout.start()
 
#sock.close()

2. [文件] server.py ~ 2KB     下载(285)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 25 10:33:44 2013
 
@author: zbg
"""
import socket
import sys
import threading
 
con = threading.Condition()
HOST = raw_input("input the server's ip adrress: ") # Symbolic name meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
data = ''
 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
s.bind((HOST, PORT))
s.listen(10)
print 'Socket now listening'
 
#Function for handling connections. This will be used to create threads
def clientThreadIn(conn, nick):
    global data
#infinite loop so that function do not terminate and thread do not end.
    while True:
    #Receiving from client
        try:
            temp = conn.recv(1024)
            if not temp:
                conn.close()
                return
            NotifyAll(temp)
            print data
        except:
            NotifyAll(nick + " leaves the room!")
            print data
            return
 
    #came out of loop
 
def NotifyAll(sss):
    global data
    if con.acquire():
        data = sss
        con.notifyAll()
        con.release()
  
def ClientThreadOut(conn, nick):
    global data
    while True:
        if con.acquire():
            con.wait()
            if data:
                try:
                    conn.send(data)
                    con.release()
                except:
                    con.release()
                    return
                     
 
while 1:
    #wait to accept a connection - blocking call
    conn, addr = s.accept()
    print 'Connected with ' + addr[0] + ':' + str(addr[1])
    nick = conn.recv(1024)
     #send only takes string
    #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
    NotifyAll('Welcome ' + nick + ' to the room!')
    print data
    print str((threading.activeCount() + 1) / 2) + ' person(s)!'
    conn.send(data)
    threading.Thread(target = clientThreadIn , args = (conn, nick)).start()
    threading.Thread(target = ClientThreadOut , args = (conn, nick)).start()
 
s.close()

3. [图片] QQ截图20131027115134.png

4. [图片] QQ截图20131027115232.png

python socket 多人聊天室的更多相关文章

  1. Python实现网络多人聊天室

    网络多人聊天室 文件结构: chatroom ├── client.py  # 客户端代码 ├── language.py  # 语言文件 ├── server.py  # 服务端代码 └── set ...

  2. Python实现网络图形化界面多人聊天室 - Windows

    Python实现网络图形化界面多人聊天室 - Windows 项目名称:网络多人聊天室图形界面版本 项目思路: server.py 服务端文件,主进程中,创建图形化界面,询问地址(主机名,端口),点击 ...

  3. Python实现网络图形化界面多人聊天室 - Linux

    网络图形化界面多人聊天室 - Linux Windows版本:https://www.cnblogs.com/noonjuan/p/12078524.html 在Python实现网络多人聊天室基础上, ...

  4. 与众不同 windows phone (31) - Communication(通信)之基于 Socket UDP 开发一个多人聊天室

    原文:与众不同 windows phone (31) - Communication(通信)之基于 Socket UDP 开发一个多人聊天室 [索引页][源码下载] 与众不同 windows phon ...

  5. 与众不同 windows phone (30) - Communication(通信)之基于 Socket TCP 开发一个多人聊天室

    原文:与众不同 windows phone (30) - Communication(通信)之基于 Socket TCP 开发一个多人聊天室 [索引页][源码下载] 与众不同 windows phon ...

  6. java socket之多人聊天室Demo

    一.功能介绍 该功能实现了一个类似QQ的最简单多人聊天室,如下图所示. 二.目录结构 三.服务端 1)SocketServer类,该类是服务端的主类,主要负责创建聊天窗口,创建监听客户端的线程: pa ...

  7. Python实现网络多人聊天室 - Windows

    项目名称:多人聊天室项目结构: client.py server.py settings.py项目思路:服务端接收客户端连接,客户端发送信息给服务端,服务端将信息发送给所有客户端.项目实现:主进程负责 ...

  8. Apache MiNa 实现多人聊天室

    Apache MiNa 实现多人聊天室 开发环境: System:Windows JavaSDK:1.6 IDE:eclipse.MyEclipse 6.6 开发依赖库: Jdk1.4+.mina-c ...

  9. 多人聊天室(Java)

    第1部分 TCP和UDP TCP:是一种可靠地传输协议,是把消息按一个个小包传递并确认消息接收成功和正确才发送下一个包,速度相对于UDP慢,但是信息准确安全:常用于一般不要求速度和需要准确发送消息的场 ...

随机推荐

  1. [转]MSSQL多列取最大或者最小值

    本文转自:http://blog.csdn.net/wufeng4552/article/details/4681510 /* lvl1 lvl2 lvl3 lvl4 lvl 4 3 4 1 3 2 ...

  2. saltstack常用语法

    一.常用语法 1.添加用户 示例1: #添加zabbix用户和组 zabbix: group.present: - name: zabbix - gid: 1001 user.present: - f ...

  3. 关于C#中async/await中的异常处理(上)

    关于C#中async/await中的异常处理(上) 2012-04-11 09:15 by 老赵, 17919 visits 在同步编程中,一旦出现错误就会抛出异常,我们可以使用try…catch来捕 ...

  4. 贯通Spark Streaming JobScheduler内幕实现和深入思考

    本节主要内容: 一.SparkStreaming Job生成深度思考 二.SparkStreaming Job生成源码解析 JobScheduler的地位非常的重要,所有的关键都在JobSchedul ...

  5. [置顶] struts2+hibernate+spring整合(annotation版)

    本博文使用struts2,hibernate,spring技术整合Web项目,同时分层封装代码,包含model层,DAO层,Service层,Action层. 在整合hibernate时使用annot ...

  6. Node.js abaike图片批量下载爬虫1.02

    //====================================================== // abaike图片批量下载爬虫1.02 // 用最近的断点续传框架改写原有1.01 ...

  7. 云计算之路-试用Azure:Azure内置的负载均衡是四层的

    当初迁移至阿里云遇到的第一个问题是在程序中通过Request.UserHostAddress得到的是负载均衡(SLB)的内网IP,而不是用户的真实IP.真实IP存储在服务器变量HTTP_X_Forwa ...

  8. OpenERP ODOO 千分位设置

    转自 :http://www.chinamaker.net/ OpenERP (ODOO)千分位设置在: 设置 > 翻译>语言 1)不同语言可以设置不同的千分位 2)格式选择: Separ ...

  9. Android Exception 8(Couldn't read row 0, col -1 from CursorWindow)

    java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Curso ...

  10. Ubuntu 下apache2 增加新的module

    http://andrew913.iteye.com/blog/398648 首先来介绍下apache的一个工具apxs.apxs是一个为Apache HTTP服务器编译和安装扩展模块的工具,用于编译 ...