Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2018
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.11 KB | None | 0 0
  1. #!/usr/bin/python2
  2. from datetime import datetime
  3. from thread import start_new_thread
  4. import socket, sys, time, os
  5. path=os.path.realpath(__file__)
  6. path=path.split("/")
  7. path[-1]=""
  8. path="/".join(path)
  9. """
  10. messages type:
  11. 0 - normal message
  12. 1 - new user in room
  13. 2 - user exit
  14. 3 - userlist
  15. 4 - system message
  16. """
  17. class bcolors:
  18. HEADER = '\033[95m'
  19. OKBLUE = '\033[94m'
  20. OKGREEN = '\033[92m'
  21. WARNING = '\033[93m'
  22. FAIL = '\033[91m'
  23. ENDC = '\033[0m'
  24. BOLD = '\033[1m'
  25. UNDERLINE = '\033[4m'
  26.  
  27. try:
  28. host=''
  29. port=int(sys.argv[1])
  30. except:
  31. print "Use:"+ sys.argv[0]+"PORT"
  32. quit()
  33.  
  34. connect=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  35. orig=(host, port)
  36. connect.bind(orig)
  37. connect.listen(1)
  38.  
  39. connect.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  40.  
  41. #max number of connetions
  42. limit=200
  43. con=["0"]*limit
  44. client=["0"]*limit
  45. nick=["0"]*limit
  46.  
  47. def getclock():
  48. time=datetime.now()
  49. clock="["+str(time.hour+100)[1::]+":"+str(time.minute+100)[1::]+":"+str(time.second+100)[1::]+"] "
  50. return clock
  51. #procedure to finish client connections
  52. def down(index):
  53. clock=getclock()
  54. print clock+"Client "+str(index)+" fell."
  55. #the value 1 indicates that the socket was in using but now is free, 0 means that the socket is virgin
  56. msg=clock+"User "+nick[index]+" exits."
  57. try:
  58. con[index].close()
  59. except Exception:
  60. print "Error! "
  61. con[index]="1"
  62. client[index]="1"
  63. nick[index]="1"
  64. j=0
  65. while(j<limit and con[j]!="0"):
  66. if(con[j]!="1" and j!=index):
  67. try:
  68. msgtp="2-"
  69. con[j].sendall(msgtp+msg)
  70. except Exception:
  71. print "Error! "
  72. j=j+1
  73.  
  74. def is_number(var):
  75. try:
  76. float(var)
  77. return True
  78. except:
  79. return False
  80. banchar=[" ", "]", "[", ":"]
  81.  
  82. def verifynick(nick):
  83. if(is_number(nick)):
  84. return False
  85. for ch in banchar:
  86. ch=str(ch)
  87. if(len(str("start"+nick+"end").split(ch))>1):
  88. return False
  89. return True
  90. #function that will manage the connection called by the index
  91. #all the connections will have a dedicated thread running this function
  92. def receive(index):
  93. try:
  94. conn=con[index]
  95.  
  96. nick[index]=conn.recv(50)
  97. Nick=nick[index]
  98. if not verifynick(Nick):
  99. msgtp="4-"
  100. conn.sendall(msgtp+"Change your nick!")
  101. down(index)
  102. print client[index],Nick,index
  103. j=0
  104. while(j<limit and con[j]!="0"):
  105. clock=getclock()
  106. if(con[j]!="1" and j!=index):
  107. message=clock+"User "+Nick+" came into the room."
  108. msgtp="1-"
  109. con[j].sendall(msgtp+message)
  110. j=j+1
  111. msgtp="4-"
  112. conn.sendall(msgtp+"You are connected!")
  113. while(1):
  114. msg=str(conn.recv(10000))
  115. if not msg:
  116. down(index)
  117. break
  118. #if the message is /who, all the users in the room will be listed
  119. if(msg=="/who"):
  120. j=0
  121. output="Users:"
  122. while(nick[j]!="0"):
  123. if(nick[j]!="1"):
  124. output=output+"\n"+nick[j]
  125. j=j+1
  126. msgtp="3-"
  127. conn.sendall(msgtp+str(output))
  128. else:
  129. clock=getclock()
  130. msg=clock+Nick+": "+msg
  131. print msg, index
  132. j=0
  133. while(j<limit and con[j]!="0"):
  134. if(con[j]!="1" and j!=index):
  135. msgtp="0-"
  136. con[j].sendall(msgtp+msg)
  137. j=j+1
  138. except Exception:
  139. try:
  140. down(index)
  141. print "Error! "
  142. except Exception:
  143. print "Error! "
  144.  
  145. def main():
  146. print bcolors.OKGREEN+"The server is ready!"+bcolors.ENDC
  147. i=0
  148. #this variable will be used to save cpu
  149. cpusave=0
  150. while(1):
  151. if(con[i]=="0" or con[i]=="1"):
  152. time.sleep(3)
  153. con[i], client[i]=connect.accept()
  154. start_new_thread(receive,(i,))
  155. if(i==limit-1):
  156. i=0
  157. else:
  158. i=i+1
  159. elif(i<limit-1):
  160. i=i+1
  161. elif(cpusave==0):
  162. i=0
  163. cpusave=1
  164. else:
  165. #here is where the variable act, after a complete loop in the list of connections
  166. #if no address is free, the program will sleep for 2 seconds before repeat the cicle
  167. i=0
  168. cpusave=0
  169. time.sleep(2)
  170.  
  171. try:
  172. main()
  173. except(KeyboardInterrupt):
  174. print "Closing the connection."
  175. i=0
  176. while(con[i]!="0" and i<limit):
  177. if(con[i]!="1"):
  178. try:
  179. con[i].shutdown(socket.SHUT_RDWR)
  180. con[i].close()
  181. except Exception:
  182. print "Error! "
  183. i=i+1
  184. connect.shutdown(socket.SHUT_RDWR)
  185. connect.close()
  186. quit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement