Guest User

Untitled

a guest
Jan 14th, 2016
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.65 KB | None | 0 0
  1. /***
  2. * @author Callum Innes, Jon Bilsbury
  3. * @title ChatServer
  4. * @description Controls the chat server
  5. */
  6.  
  7. import java.net.*;
  8. import java.util.ArrayList;
  9. import java.util.regex.Pattern;
  10. import java.io.*;
  11.  
  12. public class ChatServer implements Runnable {
  13.  
  14. private ChatServerThread clients[] = new ChatServerThread[50]; // array of current clients connected
  15. private ServerSocket serverSocket = null; // socket of the server
  16. private Thread t = null; // thread for each connected server
  17. private int noOfClients = 0; // number of clients
  18.  
  19. /**
  20. * Constructor
  21. * @param port port of the server
  22. */
  23. public ChatServer(int port) {
  24. try {
  25. System.out.println("Binding to port " + port + ", please wait ...");
  26. serverSocket = new ServerSocket(port); // server socket binds to port
  27. System.out.println("serverSocket started: " + serverSocket);
  28. start(); // start thread
  29. } catch (IOException ioe) {
  30. System.out.println("Can not bind to port " + port + ": " + ioe.getMessage());
  31. }
  32. }
  33.  
  34. /**
  35. * Always called by thread
  36. */
  37. public void run() {
  38. while (t != null) {
  39. try {
  40. System.out.println("Waiting for a client ...");
  41. addThread(serverSocket.accept());
  42. } catch (IOException ioe) {
  43. System.out.println("serverSocket accept error: " + ioe);
  44. stop();
  45. }
  46. }
  47. }
  48.  
  49. /**
  50. * Called at the start of the thread
  51. */
  52. public void start() {
  53. if (t == null) {
  54. t = new Thread(this);
  55. t.start();
  56. }
  57. }
  58.  
  59. /**
  60. * Stops the thread
  61. */
  62. public void stop() {
  63. if (t != null) {
  64. t.stop();
  65. t = null;
  66. }
  67. }
  68.  
  69. /**
  70. * finds the client from list of clients
  71. * @param ID ID of client to find
  72. * @return the location of found client
  73. */
  74. private int findClient(int ID) {
  75. for (int i = 0; i < noOfClients; i++)
  76. if (clients[i].getID() == ID)
  77. return i;
  78. return -1;
  79. }
  80.  
  81. /**
  82. * handles messages to the server and what to do with them
  83. * @param ID id of the user sending them
  84. * @param input what they are sending
  85. */
  86. public synchronized void handle(int ID, String input) {
  87. ChatServerThread client = clients[findClient(ID)];
  88. String userName = null, password = null, message = null;
  89. if (input.contains(".register")) {
  90. System.out.println("Registering " + input);
  91. String parsedInfo[] = input.split(Pattern.quote(" "));
  92. userName = parsedInfo[1];
  93. password = parsedInfo[2];
  94. registerUser(userName, password);
  95. } else if (input.contains(".login")) {
  96. String parsedInfo[] = input.split(Pattern.quote(" "));
  97. userName = parsedInfo[1];
  98. password = parsedInfo[2];
  99. if (checkLogin(userName, password) == false) {
  100. System.out.println("Telling user " + userName + " to register");
  101. client.send(".register");
  102. }
  103. client.send("SERVER: Login successful, welcome " + userName);
  104. } else if (input.charAt(0) != '.') {
  105. System.out.println(input);
  106. String parsedInfo[] = input.split(Pattern.quote("☼"));
  107. userName = parsedInfo[0];
  108. password = parsedInfo[1];
  109. message = parsedInfo[2];
  110. if (message.equals(".bye")) {
  111. client.send("Disconnecting now ...");
  112. client.send(".bye");
  113. remove(ID);
  114. } else if (message.contains("fuck")) {
  115. client.send("Rude! Timeout!\nDisconnecting now ...");
  116. client.send(".bye");
  117. remove(ID);
  118. } else if (message.length() > 160) {
  119. client.send("Client " + ID + " - too prolix!!!\nDisconnecting now ...");
  120. client.send(".bye");
  121. remove(ID);
  122. } else {
  123. for (int i = 0; i < noOfClients; i++) {
  124. clients[i].send(userName + ": " + message);
  125. System.out.println("Sending message");
  126. }
  127. }
  128. }
  129.  
  130. }
  131.  
  132. /**
  133. * registers a user by writing them to text file
  134. * @param username their username
  135. * @param password their password
  136. */
  137. public void registerUser(String username, String password) {
  138. try (FileWriter fw = new FileWriter("user_pass.txt", true);
  139. BufferedWriter bw = new BufferedWriter(fw);
  140. PrintWriter out = new PrintWriter(bw)) {
  141. out.println(username + ":" + password);
  142. } catch (IOException e) {
  143. // File writing/opening failed at some stage.
  144. }
  145. }
  146.  
  147. /**
  148. * Checks the login info given by the user
  149. * @param username username of the user
  150. * @param password password of the user
  151. * @return whether they are a member or not
  152. */
  153. public boolean checkLogin(String username, String password) {
  154. boolean valid = false;
  155.  
  156. ArrayList<String> lines = new ArrayList<String>();
  157. String line;
  158. try {
  159. BufferedReader reader = new BufferedReader(new FileReader("user_pass.txt"));
  160. while((line = reader.readLine()) != null){
  161. lines.add(line);
  162. }
  163. } catch (Exception e) {
  164. e.printStackTrace();
  165. }
  166.  
  167. String[] users = new String[lines.size()];
  168. String[] pass = new String[lines.size()];
  169.  
  170. for(int i = 0; i < lines.size(); i++){
  171. String[] output = lines.get(i).split("\\:");
  172. users[i] = output[0];
  173. pass[i] = output[1];
  174. }
  175.  
  176. for (int i = 0; i < lines.size(); i++){
  177. System.out.println(users[i] + ":" + pass[i]);
  178. if(users[i].equals(username) && pass[i].equals(password)){
  179. System.out.println("found a match");
  180. valid = true;
  181. break;
  182. }
  183. }
  184.  
  185. return valid;
  186. }
  187.  
  188. /**
  189. * removes a user from the list
  190. * @param ID user to remove
  191. */
  192. public synchronized void remove(int ID) {
  193. int pos = findClient(ID);
  194. if (pos >= 0) {
  195. ChatServerThread toTerminate = clients[pos];
  196. System.out.println("Removing client " + ID + " at " + pos);
  197. if (pos < noOfClients - 1)
  198. for (int i = pos + 1; i < noOfClients; i++)
  199. clients[i - 1] = clients[i];
  200. noOfClients--;
  201. try {
  202. toTerminate.close();
  203. } catch (IOException ioe) {
  204. System.out.println("Error closing t: " + ioe);
  205. }
  206. toTerminate.stop();
  207. }
  208. }
  209.  
  210. /**
  211. * adds a thread and pairs with user
  212. * @param socket socket of server
  213. */
  214. private void addThread(Socket socket) {
  215. if (noOfClients < clients.length) {
  216. System.out.println("Client accepted: " + socket);
  217. clients[noOfClients] = new ChatServerThread(this, socket);
  218. try {
  219. clients[noOfClients].open();
  220. clients[noOfClients].start();
  221. noOfClients++;
  222. } catch (IOException ioe) {
  223. System.out.println("Error opening thread: " + ioe);
  224. }
  225. } else
  226. System.out.println("Client refused: maximum " + clients.length + " reached.");
  227. }
  228.  
  229. /**
  230. * main method
  231. * @param args starting info
  232. */
  233. public static void main(String args[]) {
  234. ChatServer serverSocket = null;
  235. if (args.length != 1)
  236. System.out.println("Usage: java ChatServer port");
  237. else
  238. serverSocket = new ChatServer(Integer.parseInt(args[0])); // instantiate class
  239. }
  240.  
  241. }
Add Comment
Please, Sign In to add comment