欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-13 19:31:47
python socket c/s结构的聊天室应用 服务端: #!/usr/bin/env python #coding:utf8 import sock...

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