python多人聊天室_python socket 多人聊天室

2.[文件]

server.py ~ 2KB

下载(324)

# -*- 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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值