Python socket C/S结构的聊天室应用

服务端:

#!/usr/bin/env python
#coding:utf8
 
import socket,select
def 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:utf8
import 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, write_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()
华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com

稳了!魔兽国服回归的3条重磅消息!官宣时间再确认!

昨天有一位朋友在大神群里分享,自己亚服账号被封号之后居然弹出了国服的封号信息对话框。

这里面让他访问的是一个国服的战网网址,com.cn和后面的zh都非常明白地表明这就是国服战网。

而他在复制这个网址并且进行登录之后,确实是网易的网址,也就是我们熟悉的停服之后国服发布的暴雪游戏产品运营到期开放退款的说明。这是一件比较奇怪的事情,因为以前都没有出现这样的情况,现在突然提示跳转到国服战网的网址,是不是说明了简体中文客户端已经开始进行更新了呢?