Advertisement
Guest User

Untitled

a guest
Jan 21st, 2018
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. import socket
  2. import select
  3.  
  4.  
  5. #python.exe C:\Users\Yannay\PycharmProjects\serveralot\Server.py
  6.  
  7.  
  8. def send_waiting_messages(wlist, sendMsg):
  9. #get list of open sockets
  10.  
  11. for msg in sendMsg:
  12. (client_socket, data) = msg
  13.  
  14. if client_socket in wlist:
  15. client_socket.send(data)
  16. sendMsg.remove(msg)
  17.  
  18.  
  19.  
  20.  
  21.  
  22.  
  23. server_socket = socket.socket()
  24. server_socket.bind(('0.0.0.0', 13))
  25. server_socket.listen(5)
  26.  
  27. open_client_sockets = []
  28. sendMsg = []
  29.  
  30.  
  31. while True:
  32.  
  33. #get lists of clients
  34. rlist, wlist, xlist = select.select([server_socket] + open_client_sockets, open_client_sockets, [])
  35.  
  36. for s in rlist:
  37. if s is server_socket:
  38. (new_socket, address) = server_socket.accept()
  39. open_client_sockets.append(new_socket)
  40.  
  41.  
  42.  
  43. else:
  44. try:
  45. data = s.recv(1024)
  46. except:
  47. open_client_sockets.remove(s)
  48. continue
  49.  
  50.  
  51. #when client disconnecting he sends "" to the server - he sends nothing
  52. if data == "" or data == "exit":
  53. open_client_sockets.remove(s)
  54. sendMsg = [item for item in sendMsg if item[0] != s]
  55.  
  56. print "Connection with client closed \n"
  57. else:
  58. sendMsg.append((s, "Hello, " + data))
  59.  
  60. print "New data from client: "
  61. print data + "\n"
  62.  
  63.  
  64. send_waiting_messages(wlist, sendMsg)
  65.  
  66.  
  67.  
  68. server_socket.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement