Python socket C/S结构的聊天室应用
服务端:
#!/usr/bin/env python#Coding:utf8 import socket,selectdef broadcast_data (sock,message): for socket in conn_List: if socket != server_socket and socket != sock : try : socket.send(message) except : socket.close() conn_List.remove(socket) if __name__ == "__main__": conn_List = [] recv_buffer = 4096 PORT = 9999 server_socket = socket.socket(socket.AF_INET,socket.soCK_STREAM) server_socket.setsockopt(socket.soL_SOCKET,socket.so_REUSEADDR,1) #端口重用,可选 server_socket.bind(('',PORT)) server_socket.Listen(99) conn_List.append(server_socket) print "Chat server started on port " + str(PORT) while 1: read_sockets,write_sockets,error_sockets = select.select(conn_List,[],[]) for sock in read_sockets: #新建连接 if sock == server_socket: sockfd,addr = server_socket.accept() conn_List.append(sockfd) print "ClIEnt (%s,%s) connected" % addr broadcast_data(sockfd,"[%s:%s] entered room\n" % addr) #进入聊天室 else: try: data = sock.recv(recv_buffer) if data: broadcast_data(sock,"\r" + '<' + str(sock.getpeername()) + '> ' + data) except: broadcast_data(sock,"ClIEnt (%s,%s) is offline" % addr) print "ClIEnt (%s,%s) is offline" % addr sock.close() conn_List.remove(sock) continue server_socket.close()
客户端:
#!/usr/bin/env python#Coding:utf8import socket,select,string,sys def prompt() : sys.stdout.write('<You> ') sys.stdout.flush() if __name__ == "__main__": if(len(sys.argv) < 3) : print 'Usage : python chat_clIEnt.py hostname port' sys.exit() HOST = sys.argv[1] PORT = int(sys.argv[2]) s = socket.socket(socket.AF_INET,socket.soCK_STREAM) s.settimeout(2) try : s.connect((HOST,PORT)) except : print 'Unable to connect' sys.exit() print 'Connected to remote host. Start sending messages' prompt() while 1: socket_List = [sys.stdin,s] read_sockets,error_sockets = select.select(socket_List,[]) for sock in read_sockets: if sock == s: data = sock.recv(4096) if not data : print '\ndisconnected from chat server' sys.exit() else : sys.stdout.write(data) prompt() else : msg = sys.stdin.readline() s.send(msg) prompt()您可能感兴趣的文章:python的tkinter布局之简单的聊天窗口实现方法基于Python如何使用AIML搭建聊天机器人快速实现基于Python的微信聊天机器人示例代码python聊天程序实例代码分享小小聊天室Python代码实现python socket多线程通讯实例分析(聊天室)使用Python的Tornado框架实现一个一对一聊天的程序详解Python各大聊天系统的屏蔽脏话功能原理Python实现的使用telnet登陆聊天室实例python实现聊天小程序 总结
以上是内存溢出为你收集整理的Python socket C/S结构的聊天室应用实现全部内容,希望文章能够帮你解决Python socket C/S结构的聊天室应用实现所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)