标签:
最近因为考试各种复习顺便刷电视剧,感觉跟小伙伴玩的越来越不开心了,一定是最近太闲了,恩。于是想研究一下代理服务器,下载了一份代码,发现竟然还涉及到socket编程,所以把之前网络课的socket聊天室小课设拿出来整理一下思路。
代码参考资料:http://www.oschina.net/code/snippet_1387924_25928
先贴代码:
#coding:utf-8 import socket import sys import threading class server(object): __data=‘‘ #定义私有变量 __con=threading.Condition() #创建一个新的Lock对象 __sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM) #创建socket对象 def __init__(self,HOST=‘localhost‘,PORT=6008,max_num=10): #初始化socket self.__sock.bind((HOST, PORT)) self.__sock.listen(max_num) #设定最大监听数量 print ‘等待接入,侦听端口: ‘,PORT def __del__(self): #关闭socket self.__sock.close() def __NotifyAll(self,text): if self.__con.acquire(): #如果获得锁 self.__data = text self.__con.notifyAll() self.__con.release() def __ClientThreadIn(self,conn,nick): #接收消息的进程 while True: try: temp = conn.recv(1024) if not temp: conn.close() return self.__NotifyAll(temp) print self.__data except: self.__NotifyAll("Server: "+ nick + " leaves the room!") print self.__data return def __ClientThreadOut(self,conn,nick): #发送消息的进程 while True: if self.__con.acquire(): self.__con.wait() if self.__data: try: conn.send(self.__data) self.__con.release() except: self.__con.release() return def main(self): while True: conn, addr = self.__sock.accept() print ‘接到连接,client ip: ‘, addr nick = conn.recv(1024) self.__NotifyAll(‘Server: Welcome ‘ + nick + ‘ to the room!‘) # print str((threading.activeCount() + 1) / 2) + ‘ person(s)!‘ conn.send(self.__data) threading.Thread(target = self.__ClientThreadIn , args = (conn, nick)).start() threading.Thread(target = self.__ClientThreadOut , args = (conn, nick)).start() server=server() server.main()
#coding: utf-8 import socket import threading class Client(object): __nick=‘‘ __inString=‘‘ __outString = ‘‘ __sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def __init__(self,port=6008,nick=‘‘): self.__sock.connect((‘localhost‘, port)) if nick!=‘‘: self.__nick = nick else: self.__nick = raw_input("input your nickname: ") self.__sock.send(self.__nick) def __del__(self): self.__sock.close() def main(self): thin = threading.Thread(target = self.__DealIn).start() thout = threading.Thread(target = self.__DealOut).start() def __DealOut(self): while True: self.__outString = raw_input() self.__outString = self.__nick + ‘: ‘ + self.__outString self.__sock.send(self.__outString) def __DealIn(self): while True: try: self.__inString = self.__sock.recv(1024) if not self.__inString: break if self.__inString!=self.__outString: print self.__inString except: break client=Client() client.main()
标签:
原文地址:http://www.cnblogs.com/kuoaidebb/p/4200099.html