Advertisement
Guest User

Untitled

a guest
Nov 28th, 2014
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.17 KB | None | 0 0
  1. import socket
  2. import select
  3. import sys
  4. #http://stackoverflow.com/questions/18785482/python-non-blocking-peer-to-peer-chat-socket-error-errno-32-broken-pipe
  5. CONNECTION_LIST = []
  6. RECV_BUFFER = 4096
  7. PORT = 30050
  8.  
  9. server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  10. server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  11. server_socket.bind(('0.0.0.0', PORT))
  12. server_socket.listen(5)
  13.  
  14. CONNECTION_LIST.append(server_socket)
  15. CONNECTION_LIST.append(sys.stdin)
  16.  
  17.  
  18. print 'Chat server Started on port ' + str(PORT)
  19.  
  20.  
  21. def broadcast_data(sock, message):
  22.  
  23.     for socket in CONNECTION_LIST:
  24.         if socket != server_socket and socket != sock and socket != sys.stdin:
  25.             try:
  26.                 socket.send(message)
  27.             except:
  28.                 socket.close()
  29.                 CONNECTION_LIST.remove(socket)
  30.  
  31. def prompt() :
  32.     sys.stdout.write('<You> ')
  33.     sys.stdout.flush()
  34.  
  35. prompt()
  36.  
  37. while True:
  38.     read_sockets, write_sockets, error_sockets = select.select(CONNECTION_LIST, [], []) # NON_blocking I/O with 0
  39.  
  40.     for sock in read_sockets:
  41.         if sock == server_socket:
  42.             # new Connection
  43.             sockfd, addr = server_socket.accept()
  44.             CONNECTION_LIST.append(sockfd)
  45.             print 'Clinet (%s, %s) connected ' % addr
  46.             broadcast_data(sockfd, "[%s:%s] entered room" % addr)
  47.         elif sock == sys.stdin:
  48.             msg = sys.stdin.readline()
  49.             broadcast_data(sock, 'Server > ' + msg)
  50.             prompt()
  51.         else:
  52.             try:
  53.                 #In Windows, sometimes when a TCP program closes abruptly,
  54.                 # a "Connection reset by peer" exception will be thrown
  55.                 data = sock.recv(RECV_BUFFER)
  56.                 if data:
  57.                     print "\r" + '<' + str(sock.getpeername()) + '>' + data
  58.                     broadcast_data(sock, "\r" + '<' + str(sock.getpeername()) + '>' + data)
  59.             except:
  60.                 broadcast_data(sock, "Client (%s, %s) is offline" % addr)
  61.                
  62. print "Client (%s, %s) is offline" % addr
  63.                 sock.close()
  64.                 CONNECTION_LIST.remove(sock)
  65.                 continue
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement