Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on Jul 21st, 2012  |  syntax: None  |  size: 5.06 KB  |  views: 40  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. import os
  2. import re
  3. import socket
  4. import sys
  5. import time
  6. server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create socket
  7. server_socket.bind(("", 9020)) #Bind server to this socket
  8. server_socket.listen(4) #Max number of queued connections
  9. # Welcome message
  10. print ("TCP chat server now awaiting client connection on port 9020...")
  11. chat_log = [] #Contains chat log
  12. time = time.strftime('%l:%M %p %Z on %b %d, %Y') #Server start time formatted nicely
  13. start_time = str(time) #Convert server start time to string
  14. username = "ChatUser" #Default server username if user does not provide one
  15. # Support ~2^x client connections, where x is the number of process forks
  16. os.fork()
  17. os.fork()
  18. os.fork()
  19. # This variable contains the help documentation for the "help" command
  20. chatHelp = ("The chat server accepts the following commands:\n"
  21. + "adios Closes the program\n"
  22. + "connection Shows client connection info (IP, port)\n"
  23. + "get Returns complete chat log\n"
  24. + "getrange <#> <#> Get chat log entries from <#> to <#> (starts at 1)\n"
  25. + "help Lists valid commands\n"
  26. + "name: <text> Sets your username to <text>\n"
  27. + "test: <text> Echo data back to you <text>\n"
  28. + "time Shows time when server was initiated\n"
  29. + "push: <text> Add <text> to chat log\n"
  30. + "save Save chat log to file\n")
  31. while 1:
  32.  # Accept connection
  33.  client_socket, address = server_socket.accept()
  34.  
  35.  # Print connection info from client for server log
  36.  print ("Received connection from client at"), address
  37. # Used in the connection command function (client request) below
  38.  connection = str(address)
  39. # Send welcome string to client
  40.  client_socket.send("Welcome to Nigel's chat room! You are logged in as ChatUser.\n Type help for a list of valid commands.\n")
  41. # Loop indefinitely while server running
  42.  while 1:
  43.     data = client_socket.recv(2048) #Receive client data into buffer
  44.  process_data = data.lower() #Lowercase received data for processing
  45.  print ("Data received from client>>"), process_data #Print data received from client for log reference
  46.  
  47.  # Functions for the received commands (I use the find library to reduce compatibility errors with other languages)
  48.  # ---"adios" command function---
  49. if (process_data.find("adios") == 0):
  50.      client_socket.close() #Close socket connection
  51.  print ("<Ctrl+C to exit.>>")
  52.  break;
  53.  
  54.  # ---"connection:" command function---
  55. elif(process_data.find("connection") == 0):
  56.  client_socket.send("Client connection info: " + connection + "\n")
  57.  print "User requested connection information"
  58.  
  59.  # ---"getrange" command function w/ regular expression filtering (must be BEFORE "get" command function)---
  60.  elif(re.match(r'getrange\s+(\d+)\s+(\d+)',process_data)): # Regex to find correct match with dynamic numbers input
  61.  match = re.match(r'getrange\s+(\d+)\s+(\d+)',process_data)
  62.  getValue = "Chat log from range "+ match.group(1) + " and " + match.group(2) + ":\n" # Grab first and second range number provided by client
  63.  if(len(chat_log) >= int(match.group(1)) and len(chat_log) >= int(match.group(2))): # Check to see if chat log extends to given range
  64.  count = int(match.group(1)) - 1
  65.  while(count < int(match.group(2))):
  66.  getValue += chat_log[count] + "\n"
  67.  count += 1
  68.  else:
  69.  getValue += "<>\n" #No data in range provided by client
  70.  client_socket.send(getValue) #Send results to client
  71. # ---"get" command function---
  72.  elif(process_data.find("get") == 0):
  73.  log = "Chat log: \n"
  74.  for item in chat_log:
  75.  log += item+" \n"
  76.  client_socket.send(log)
  77.  
  78.  # ---"help:" command function---
  79.  elif(process_data.find("help") == 0):
  80.  client_socket.send(chatHelp + "\n")
  81.  print "User requested help"
  82.  
  83.  # ---"name:" command function---
  84.  elif(process_data.find("name:") == 0):
  85.  username = data[5:].strip() #Only grab the value client set (not "name:")
  86.  client_socket.send("Username set to: " + data[5:] + "\n")
  87.  
  88.  # ---"test:" command function---
  89.  elif(process_data.find("test:") == 0):
  90.  client_socket.send(data[5:]+"\n") #Echo last 5 elements to client
  91.  print data
  92.  
  93.  # ---"time" command function---
  94.  elif(process_data.find("time") == 0):
  95.  client_socket.send("Chat server was started at: " + start_time + "\n")
  96.  print "User requested server start time"
  97.  
  98.  # ---"save" command function---
  99.  elif(process_data.find("save") == 0):
  100.  print "(Saving chat log to file)"
  101.  client_socket.send("Saving chat log to file..." + "\n")
  102.  filename = "chat.log"
  103.  file = open(filename,"w") #Create file
  104.  for item in chat_log: #Loop through elements in chat_log
  105.  file.write("%s\n" % item) #Write elements one by one on a new line
  106.  file.close() #Close/write file
  107.  
  108.  # ---"push" command function---
  109.  elif(process_data.find("push:") == 0):
  110.  print "(Pushing data to chat log)"
  111.  if(username != ""):
  112.  chat_log.append(username + ": " + data[5:].strip()) #Save actual chat text to log (not "push:")
  113.  else:
  114.  chat_log.append(data[5:].strip())
  115.  client_socket.send("OK\n")
  116.  else:
  117.  print "<<Unknown Data Received>>",data #Server log
  118.  try:
  119.  client_socket.send("Unrecognized command: " + data + "") #Advise client of invalid command
  120.  except socket.error, e:
  121.  print "<<Ctrl+C to exit>>" #Server log
  122.  break;