python socket 多人聊天室

參考來源(其實我從上面復制了一點):
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????

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/395320.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/395320.shtml
英文地址,請注明出處:http://en.pswp.cn/news/395320.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

json數據轉換成表格_電子表格會讓您失望嗎? 將行數據轉換為JSON樹很容易。

json數據轉換成表格Like many of you, I often have to take the result of SQL queries and convert the rowsets to JSON data objects. Sometimes I have to do the same with CSV files from spreadsheets. The transformation process can be a hassle, though anyone can…

mxm智能教育機器人無法智能對話_零代碼使用騰訊TBP打造智能對話機器人

點擊觀看大咖分享心疼你獨自一人承擔生活的苦難&#xff0c;寂寞夜里陪伴你的只剩無人傾訴的壓抑和無處安放的焦慮。養個寵物&#xff0c;它卻不能get到你的“寵言寵語”。找個伴侶&#xff0c;還要浪費吵架的時間和精力。回到家里&#xff0c;只能浸泡在“循環嘮叨式“母愛的沐…

MyGeneration代碼生成工具

使用MyGeneration 生成代碼&#xff1a;轉自http://www.cnblogs.com/jack-liang/archive/2011/08/18/2144066.html我們經常用數據訪問層和業務邏輯層&#xff0c;用MyGeneration就可以自動生成這些代碼&#xff0c;我們可以不用手動寫代碼了。比如數據訪問層&#xff0c;我們需…

數據庫部分重點內容回顧

1.什么是聚集索引? 樹形結構將數據組織和存儲起來,起到加速查詢的效果 2.主鍵索引怎么添加? (1)聚集索引(主鍵索引)的添加方式,創建時添加 方式一: Create table t1( id int primary key, ) 方式二: Create table t1( Id int, Primary key(id) ) (2)唯一索引創建時添加: 方式…

keytool 錯誤: java.io.IOException: Keystore was tampered with, or password was incorrect

1.這里需要輸入的密碼不是證書的密碼執行keytool -import -keystore - file 這個命令提示需要輸入密碼進入jdk的bin目錄&#xff0c;執行以下腳本&#xff0c;keytool -import -alias saltapi -keystore /Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre…

怎么更換鎖定計算機的圖片,Win10系統下怎樣對鎖定界面的背景圖片進行更換

用戶在喚醒睡眠狀態的win10系統時&#xff0c;最先看到就是鎖定界面。在界面中&#xff0c;一般有時間日期、星期幾&#xff0c;及默認的背景圖片。那么&#xff0c;win10系統鎖定界面中的背景圖片可以修改嗎&#xff1f;下面&#xff0c;小編就給大家分享Win10系統更換鎖定界面…

輸電線路巡檢機器人PPT_“高空大師”來了!架空輸電線路智能巡檢機器人在寧波投運...

“鄞州區220千伏天田4480線一切正常……”17日上午&#xff0c;隨著一臺智能巡檢機器人穩穩地停靠在鐵塔邊&#xff0c;標志著我省首臺架空輸電線路智能巡檢機器人在寧波率先投入運行&#xff0c;為電網安全運行請來了一位“高空大師”。近年來&#xff0c;無人機代替電力工人巡…

HDU 6325 Problem G. Interstellar Travel(凸包)

題意: 給你n個點,第一個點一定是(0,0)&#xff0c;最后一個點縱坐標yn一定是0&#xff0c;中間的點的橫坐標一定都是在(0,xn)之間的 然后從第一個點開始飛行&#xff0c;每次飛到下一個點j&#xff0c;你花費的價值就是xi*yj-xj*yi&#xff0c;并且這里每一次飛行必須滿足xi<…

UIView封裝動畫--iOS利用系統提供方法來做關鍵幀動畫

iOS利用系統提供方法來做關鍵幀動畫 ios7以后才有用。 /*關鍵幀動畫options:UIViewKeyframeAnimationOptions類型*/[UIView animateKeyframesWithDuration:5.0 delay:0 options: UIViewAnimationOptionCurveLinear| UIViewAnimationOptionCurveLinear animations:^{//第二個關鍵…

JavaScript —從回調到異步/等待

JavaScript is synchronous. This means that it will execute your code block by order after hoisting. Before the code executes, var and function declarations are “hoisted” to the top of their scope.JavaScript是同步的。 這意味著它將在提升后按順序執行代碼塊。…

關于解決工作中的自動化環境搭建的解決方案(序)

時間&#xff1a;2015~2017 之前的自動化搭建平臺&#xff1a;robotest 安裝工具&#xff1a;jdk1.8,robotest 這種工具反正超級好用&#xff0c;華為方搞得工具&#xff0c;前臺操作超級傻瓜。會點xpatch&#xff0c;一些東西根本不在話下。但是坑爹的就是&#xff0c;出了外包…

xshell安裝mysql步驟_mysql主從復制

前期提要&#xff1a;三年前雙11買的阿里云今年到期了&#xff0c;win2012的&#xff0c;上面mysql數據庫里記著自己的一些記賬數據&#xff0c;上一年雙11買了騰訊云的&#xff0c;centos7.7, 想學學MYSQL的復制功能&#xff0c;今天趁著無BUG可擼&#xff0c;試著配置了一下&…

大專學計算機維修,《計算機維修與網絡工程》大專學歷班

語文、數學、計算機英語、公文寫作等辦公自動化指法訓練、英文打字、智能拼音及高速五筆字型中文打字、windows操作、Word2003文字處理軟件、Excel2003電子表格、Powerpoint2003幻燈片制作、Internet網絡的上網方法、瀏覽、下載、電子郵件收發等。本班學習完畢&#xff0c;可獨…

webpack指定第三方模塊的查找路徑

通常我們會使用一些地方模塊在我們的項目中&#xff0c;比如bootstrap import bootstrap 導入的bootstrap默認會查找當前目錄的node_modules文件&#xff0c;但是如果這個文件沒有&#xff0c;會依次往上級模塊查找&#xff0c;直到到C盤的根目錄為止&#xff0c;可以通過webpa…

我的第一個安卓應用程序_我如何設計我的第一個應用程序

我的第一個安卓應用程序by Daniel Novykov丹尼爾諾維科夫(Daniel Novykov) 我如何設計我的第一個應用程序 (How I Designed My First App) This is a story about building a product, what went wrong, and how it changed my career into Design.這是一個有關構建產品&#…

Appium——主從控制執行

1.客戶端(Eclipse)機器A&#xff0c; 服務端(appium、Genymotion)機器B 2.設置Appium&#xff0c;Server Address為192.168.17.123&#xff0c;重新啟動Appium 3.在客戶端機器A瀏覽器中輸入&#xff1a;http://192.168.17.123:4723/wd/hub&#xff0c; 說明配置成功。 JAVA代碼…

Python學習-03(集合,文件,編碼)

上周復習&#xff1a; 列表增刪改查 元祖是可讀列表 字符串操作 字典是無序的&#xff0c;通過key來找值。字典可以嵌套列表和字典 本周內容&#xff1a;集合--文件---字符編碼 集合引入&#xff1a; #隨機生成20個小于20的數&#xff0c;輸出所有的數&#xff0c;# 要求重復…

安裝centos7失敗認不到硬盤_CentOS7 用U盤安裝卡住無法進入安裝界面解決方案

使用U盤安裝Centos系統找不到U盤解決方案補充&#xff1a;1、制作U盤啟動盤請參考&#xff1a;使用UltraISO(軟碟通)制作ubuntu U盤啟動盤如果你安裝centos7出現了下圖這種情況不用擔心&#xff0c;是因為安裝centos7時找不到U盤稍等一下&#xff0c;如下圖等到出現命令行時。輸…

Django橫向二級導航欄(鼠標懸空事件)

1 <!DOCTYPE html>2 <html lang"en" xmlns"http://www.w3.org/1999/html">3 <head>4 <meta charset"UTF-8">5 <title>{% block title %} base模板 {% endblock title%}</title>6 <style >…

浙江大學計算機學院1702班,測控1702:傳道授業解惑 此間師者真情

2017年9月11日晚8:00&#xff0c;電氣與信息工程學院測控技術與儀器1702班在德智學生公寓的天臺上開展了一場別開生面的班主任見面交流會。測控1702班班主任文一章博士、電氣院2017級本科輔導員金晶老師以及測控1702班的同學們參加了此次見面會。測控1702班班主任文一章1991年出…