Advertisement
Guest User

Untitled

a guest
Mar 10th, 2016
346
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.52 KB | None | 0 0
  1. //Student Name: Adam McGivern
  2.  
  3. //Student Number: 40086043
  4. //Module Code: CSC 2008
  5. //Practical Day: Monday
  6. //Email: amcgivern11@qub.ac.uk
  7.  
  8. import java.awt.*;
  9. import java.awt.event.*;
  10. import javax.swing.*;
  11. import java.io.*;
  12. import java.net.*;
  13. import java.util.ArrayList;
  14. import java.util.Arrays;
  15.  
  16. @SuppressWarnings("serial")
  17. public class Chat_Server extends JFrame
  18. { // total number of clients that can be logged on to the message service
  19. final int NO_OF_CLIENTS = 4;
  20.  
  21. // this ArrayList will store the client threads
  22. ArrayList<Chat_ServerThread> chatClients = new ArrayList<Chat_ServerThread>();
  23.  
  24. // arrays containing valid names and passwords
  25. String Rules = "Welcome to the CSC2008 Chat Server. Only users who are older than your country's age of maturity have permission to use the service. All interactions between clients are monitored and recorded on this server. Any messages containing defamatory content will be referred to the authorities. You have been warned! Questions? Contact us at no.one@cares.com. Please enjoy and remember there is a world outside without chat clients and servers! ";
  26. String realNames[] = {"Adam Smyth", "Bill Allen", "Cathy Clark", "Davina Doe"};
  27. String passwords[] = {"LuQezz169", "amG4tyz", "Dw1wU9wy", "Fre195Ufm"};
  28.  
  29. // array containing valid chat tags
  30. String [] chattag = {"Arken", "Ben", "Darklark", "Free", "Group"};
  31.  
  32. // this array indicates whether a client is currently logged on
  33. boolean loggedOn[] = new boolean[NO_OF_CLIENTS];
  34.  
  35. // GUI components
  36. JTextArea outputArea;
  37.  
  38. // declaration
  39. ServerSocket serverSocket;
  40. DataInputStream serverInputStream;
  41. DataOutputStream serverOutputStream;
  42.  
  43.  
  44. public Chat_Server()
  45. { super("Chat_Server");
  46. addWindowListener
  47. ( new WindowAdapter()
  48. { public void windowClosing(WindowEvent e)
  49. { System.exit(0);
  50. }
  51. }
  52. );
  53.  
  54. try
  55. { // get a serversocket
  56. serverSocket = new ServerSocket(7500);
  57.  
  58. }
  59. catch(IOException e) // thrown by ServerSocket
  60. { System.out.println(e);
  61. System.exit(1);
  62. }
  63.  
  64. // create and add GUI components
  65. Container c = getContentPane();
  66. c.setLayout(new FlowLayout());
  67. // add text output area
  68. outputArea = new JTextArea(20,33);
  69. outputArea.setEditable(false);
  70. outputArea.setLineWrap(true);
  71. outputArea.setWrapStyleWord(true);
  72. c.add(outputArea);
  73. c.add(new JScrollPane(outputArea));
  74. setSize(420,370);
  75. setResizable(false);
  76. setVisible(true);
  77. }
  78.  
  79. void getClients()
  80. { // add message to server output area
  81. addOutput("Chat Sever is up and waiting for a connection...");
  82. int userCount = 0;
  83. while(userCount < NO_OF_CLIENTS)
  84. { try
  85. { /* client has attempted to get a connection to server,
  86. create a socket to communicate with this client */
  87. Socket client = serverSocket.accept();
  88.  
  89. // get input & output streams
  90. ObjectInputStream serverInputStream = new ObjectInputStream(client.getInputStream());
  91. ObjectOutputStream serverOutputStream = new ObjectOutputStream(client.getOutputStream());
  92.  
  93. // add message to server output area
  94. addOutput("Got a connection request from client");
  95.  
  96. // read encrypted username from input stream & decrypt
  97. EncryptedMessage usname = (EncryptedMessage)serverInputStream.readObject();
  98. usname.decrypt();
  99.  
  100. // read encrypted password from input stream & decrypt
  101. EncryptedMessage psword = (EncryptedMessage)serverInputStream.readObject();
  102. psword.decrypt();
  103.  
  104.  
  105. // add messages to server output area
  106. addOutput("decrypted username : " + usname.getMessage());
  107. addOutput("decrypted password : " + psword.getMessage());
  108.  
  109. String u = usname.getMessage();
  110. String p = psword.getMessage();
  111. boolean valid = false;
  112. addOutput("Login details received from client" +(userCount+1) + ", " + u);
  113. int pos = -1;
  114. // Arrays.binarySearch(names, u);
  115. for(int i = 0; i < realNames.length; ++i)
  116. {
  117.  
  118. if(u.equals(realNames[i]) && p.equals(passwords[i]) && !loggedOn[i])
  119. {
  120. valid = true;
  121. pos = i;
  122. }
  123. }
  124.  
  125. //addOutput("Login details received from client" +(userCount+1));
  126.  
  127. if(valid)
  128. { if(passwords[pos].equals(p) && !loggedOn[pos])
  129. { addOutput("Login details received from client" + (userCount+1) + ", " + u + " are valid");
  130. addOutput("Client " + u + " is known as " + chattag[pos]);
  131. valid = true;
  132. loggedOn[pos] = true;
  133. // send Boolean value true to client
  134. serverOutputStream.writeObject(new Boolean(true));
  135. //serverOutputStream.writeObject(u`);
  136.  
  137.  
  138. // add this new thread to the array list
  139. Chat_ServerThread chatClient = new Chat_ServerThread (serverInputStream, serverOutputStream, usname.getMessage(), chattag[pos]);
  140. chatClients.add(chatClient);
  141.  
  142. // start thread - execution of the thread will begin at method run
  143. chatClient.start();
  144.  
  145. userCount++;
  146. }
  147. }
  148. else
  149. { /* user is not registered therefore write a Boolean value
  150. false to the output stream */
  151. serverOutputStream.writeObject(new Boolean(false));
  152. addOutput("Login details received from client " + (userCount+1) + ", " + u + " are invalid");
  153. }
  154. }
  155. catch(ClassNotFoundException e) // thrown by method readObject
  156. { System.out.println(e);
  157. System.exit(1);
  158. }
  159. catch(IOException e) // thrown by Socket
  160. { System.out.println(e);
  161. System.exit(1);
  162. }
  163. }
  164. }
  165.  
  166. void addOutput(String s)
  167. { // add message to text output area
  168. outputArea.append(s + "\n");
  169. outputArea.setCaretPosition(outputArea.getText().length());
  170. }
  171.  
  172. // main method of class Chat_Server
  173. public static void main(String args[])
  174. { Chat_Server chatServer = new Chat_Server();
  175. chatServer.getClients();
  176. }
  177.  
  178. // beginning of class Chat_ServerThread
  179. private class Chat_ServerThread extends Thread
  180. { // What to declare?
  181. ObjectInputStream threadInputStream;
  182. ObjectOutputStream threadOutputStream;
  183. String clientName;
  184. String chatterName;
  185.  
  186.  
  187. public Chat_ServerThread(ObjectInputStream in, ObjectOutputStream out, String cname, String ctName)
  188. { // initialise input stream
  189. threadInputStream = in;
  190.  
  191. // initialise output stream
  192. threadOutputStream = out;
  193.  
  194. // initialise user name
  195. clientName = cname;
  196.  
  197. // initialise chat name
  198. chatterName = ctName;
  199. }
  200.  
  201. CompressedMessage getCompressedMessage(String str)
  202. { // create & return a compressed message
  203. CompressedMessage message = new CompressedMessage(str);
  204. message.compress();
  205.  
  206. return message;
  207. }
  208.  
  209. // when method start() is called thread execution will begin in this method
  210. public void run()
  211. { try
  212. { //send greeting to this client
  213. threadOutputStream.writeObject((getCompressedMessage(Rules +"\n" + "Welcome to the chat server " + clientName)));
  214.  
  215. // inform this client of other clients online
  216. threadOutputStream.writeObject(getCompressedMessage("online" + getChatClients()));
  217. // output to server window
  218. addOutput(clientName + " known as " + chatterName + " has joined");
  219. // inform other clients that this client has joined
  220. sendMessage("join" + chatterName);
  221.  
  222. boolean quit = false; //broadcast = false;
  223. // this loop will continue until the client quits the chat service
  224. while(!quit)
  225. { // read next compressed message from client
  226. CompressedMessage nextMessage = (CompressedMessage)threadInputStream.readObject();
  227.  
  228. // decompress message
  229. nextMessage.decompress();
  230.  
  231. // retrieve decompressed message
  232. String fromClient = nextMessage.getMessage();
  233.  
  234. // find position of separating character
  235. int foundPos = fromClient.indexOf('#');
  236.  
  237. // list of recipients for message
  238. String sendTo = fromClient.substring(0,foundPos);
  239.  
  240. // message to be sent to recipients
  241. String message = fromClient.substring(foundPos+1);
  242. System.out.println(message);
  243.  
  244. // if the message is "quit" then this client wishes to leave the chat service
  245. if(message.equals("quit "))
  246. { // add message to server output area
  247. addOutput(clientName + " has " + message);
  248.  
  249. // inform other clients that this client has quit
  250. sendMessage("quit" + chatterName);
  251.  
  252. //send "goodbye" message to this client
  253. threadOutputStream.writeObject(getCompressedMessage("Goodbye"));
  254.  
  255. // remove this client from the list of clients
  256. remove(chatterName);
  257.  
  258.  
  259. quit = true;
  260. }
  261. else
  262. { // add message to server output area
  263. addOutput(clientName + ">> " + message);
  264. // split string to separate recipients names
  265. String[] recipients = sendTo.split(",\\s*");
  266. // sort this array to use binarySearch
  267. Arrays.sort(recipients);
  268. // identify if this message is to be sent to all other clients
  269. foundPos = Arrays.binarySearch(recipients, chattag[chattag.length-1]);
  270. if(foundPos >= 0)
  271. // send this message to all other clients
  272. sendMessage(chatterName + ">> " + message);
  273. else
  274. // send this message to all clients in recipients array
  275. sendMessage(chatterName + ">> " + message, recipients);
  276. }
  277. } // end while
  278. // close input stream
  279. threadInputStream.close();
  280. // close output stream
  281. threadOutputStream.close();
  282. }
  283. catch(IOException e) // thrown by method readObject, writeObject, close
  284. { System.out.println(e);
  285. System.exit(1);
  286. }
  287. catch(ClassNotFoundException e) // thrown by method readObject
  288. { System.out.println(e);
  289. System.exit(1);
  290. }
  291. }
  292.  
  293. /* this method returns a list of the names of all the
  294. clients currently joined excluding this client */
  295. String getChatClients()
  296. { String allClients = "";
  297. synchronized(chatClients)
  298. { /* traverse list of threads & add value of
  299. instance variable name of each thread */
  300. for (Chat_ServerThread sThread : chatClients)
  301. { if(!sThread.chatterName.equals(chatterName))
  302. allClients += sThread.chatterName + ",";
  303. }
  304. }
  305. if(allClients.equals(""))
  306. allClients = "none";
  307. return allClients;
  308. }
  309.  
  310. /* this method sends the current message to all the
  311. clients currently joined excluding this client */
  312. void sendMessage(String str)
  313. { synchronized(chatClients)
  314. { /* traverse list of threads & send message
  315. to all clients */
  316. for (Chat_ServerThread sThread : chatClients)
  317. { if(!sThread.chatterName.equals(chatterName))
  318. { try
  319. { sThread.threadOutputStream.writeObject(getCompressedMessage(str));
  320. }
  321. catch(IOException e) // thrown by method writeObject
  322. { System.out.println(e);
  323. System.exit(1);
  324. }
  325. }
  326. }
  327. }
  328. }
  329.  
  330. /* this method sends the current message to all the
  331. clients in the recipients array */
  332. void sendMessage(String str, String[] rec)
  333. { synchronized(chatClients)
  334. { /* traverse list of threads - if a match is found
  335. with recipients name send message to that client */
  336. for(Chat_ServerThread sThread : chatClients)
  337. { if(Arrays.binarySearch(rec, sThread.chatterName) >= 0)
  338. { try
  339. { sThread.threadOutputStream.writeObject(getCompressedMessage(str));
  340. }
  341. catch(IOException e) // thrown by method writeObject
  342. { System.out.println(e);
  343. System.exit(1);
  344. }
  345. }
  346. }
  347. }
  348. }
  349.  
  350. /* this method removes this client's thread
  351. from the list */
  352. void remove(String name)
  353. { synchronized(chatClients)
  354. { int pos = -1;
  355. /* traverse list of threads & find position of
  356. this client's thread in the list */
  357. for(int i = 0; i < chatClients.size(); i++)
  358. { if(chatClients.get(i).chatterName.equals(name))
  359. pos = i;
  360. }
  361. if(pos != -1)
  362. // remove this client's thread
  363. chatClients.remove(pos);
  364. //make them offline
  365. loggedOn[pos] = false;
  366. }
  367. }
  368. } // end of class Chat_ServerThread
  369. } // end of class Chat_Server
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement