Advertisement
KasperKnudsen

Untitled

Dec 4th, 2018
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.00 KB | None | 0 0
  1. package labbserver;
  2.  
  3. import java.io.*;
  4. import java.net.*;
  5. import java.awt.*;
  6. import java.awt.event.*;
  7. import java.nio.charset.StandardCharsets;
  8. import java.nio.file.*;
  9. import java.nio.file.Files;
  10. import java.nio.file.Paths;
  11. import java.util.ArrayList;
  12. import java.util.Collections;
  13. import java.util.Iterator;
  14. import java.util.Map;
  15. import java.util.Scanner;
  16. import java.util.logging.Level;
  17. import java.util.logging.Logger;
  18. import javax.swing.*;
  19. import javax.swing.JDialog;
  20. import javax.swing.JFrame;
  21.  
  22.  
  23. public class LabbServer extends JFrame {
  24.  
  25. public static void main(String[] args) {
  26. //boolean clientOrServer = true; //server runs if true
  27. boolean clientOrServer = false; // client runs if false
  28.  
  29.  
  30.  
  31.  
  32. if (clientOrServer) {
  33.  
  34. LabbServer serverChat = new LabbServer();
  35. serverChat.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  36. serverChat.startRunning();
  37. } else {
  38.  
  39.  
  40. comboBoxClass box = new comboBoxClass();
  41.  
  42.  
  43. //Client clientChat = new Client(Client.getPort_IP());
  44. //clientChat.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  45. //clientChat.startRunning();
  46.  
  47.  
  48. }
  49.  
  50. }
  51.  
  52. private JTextField userText;
  53. private JTextArea chatWindow;
  54. private ObjectOutputStream output;
  55. private ObjectInputStream input;
  56. private Socket connection;
  57. private ServerSocket server;
  58. JButton button = new JButton("End Chat");
  59. static JDialog dialog;
  60.  
  61. public LabbServer() {
  62. setTitle("Server");
  63.  
  64. userText = new JTextField();
  65. userText.setEditable(false);
  66. userText.addActionListener(
  67. new ActionListener() {
  68. public void actionPerformed(ActionEvent event) {
  69. sendMessage(event.getActionCommand());
  70. userText.setText("");
  71. }
  72. }
  73. );
  74. add(userText, BorderLayout.NORTH);
  75. chatWindow = new JTextArea();
  76. add(new JScrollPane(chatWindow), BorderLayout.CENTER);
  77. setSize(800, 400);
  78. setVisible(true);
  79.  
  80. add(button, BorderLayout.SOUTH);
  81. whenClickButton();
  82.  
  83. }
  84.  
  85. public void startRunning() {
  86. try {
  87. server = new ServerSocket(6666, 10); //6789 är port-numret, 10 personer kan connecta.
  88. waitForConnection();
  89. setUpStreams();
  90. whileChatting();
  91.  
  92. } catch (EOFException eofException) {
  93. showMessage("\n Server ended the connection!");
  94.  
  95. } catch (IOException ioException) {
  96. ioException.printStackTrace();
  97. } finally {
  98. closeCrap();
  99. System.exit(0);
  100. }
  101. }
  102.  
  103. private void waitForConnection() throws IOException {
  104. showMessage("Waiting for someone to connect");
  105. connection = server.accept();
  106. showMessage("Now connected to " + connection.getInetAddress().getHostName());
  107. }
  108.  
  109. private void setUpStreams() throws IOException {
  110. output = new ObjectOutputStream(connection.getOutputStream());
  111. output.flush();
  112. input = new ObjectInputStream(connection.getInputStream());
  113. showMessage("\n Streams are now setup! \n");
  114.  
  115. }
  116.  
  117. // While chatting with client
  118. private void whileChatting() throws IOException {
  119. String message = "You are now connected";
  120. sendMessage(message);
  121. ableToType(true);
  122. do {
  123. try {
  124. message = (String) input.readObject();
  125. showMessage("\n" + message);
  126. } catch (ClassNotFoundException classNotFoundException) {
  127. showMessage("\n I dont know that object type");
  128. }
  129.  
  130. } while (!message.equals("CLIENT - END"));
  131. }
  132.  
  133. //Close streams and sockets.
  134. private void closeCrap() {
  135. showMessage("\n Closing connection");
  136. ableToType(false);
  137. try {
  138. output.close();
  139. input.close();
  140. connection.close();
  141. } catch (IOException ioException) {
  142. ioException.printStackTrace();
  143. }
  144. }
  145.  
  146. private void sendMessage(String message) {
  147. try {
  148. output.writeObject("SERVER - " + message); //output skickar medanden ut från servern.
  149. output.flush();
  150. showMessage("\nSERVER - " + message);
  151.  
  152. } catch (IOException ioException) {
  153. chatWindow.append("\n Something messed up in sending the message");
  154. }
  155. }
  156.  
  157. //Visar hela historiken i chaten, lägger till nya medelanden på skärmen hela tiden.
  158. private void showMessage(final String message) {
  159.  
  160. SwingUtilities.invokeLater( //Uppdeterar hela tiden.
  161. new Runnable() {
  162. public void run() {
  163. chatWindow.append(message);
  164. }
  165. }
  166. );
  167. }
  168.  
  169. private void ableToType(final boolean tof) { //tof = true or false
  170. SwingUtilities.invokeLater(
  171. new Runnable() {
  172. public void run() {
  173. userText.setEditable(tof); //If true its editable. False it is not.
  174. }
  175. }
  176. );
  177. }
  178.  
  179. void whenClickButton() {
  180. button.addActionListener(new ActionListener() {
  181. @Override
  182. public void actionPerformed(ActionEvent e) {
  183. System.exit(0);
  184. }
  185. }
  186. );
  187. }
  188. }
  189.  
  190. /* Kasper Knudsen & Sara Särnblad STS 2A */
  191. class Client extends JFrame {
  192.  
  193. private JTextField userText;
  194. private JTextArea chatWindow;
  195. private ObjectOutputStream output;
  196. private ObjectInputStream input;
  197. private String message = "";
  198. private Socket connection;
  199. int contactPort;
  200. String serverIP;
  201. int returnVal;
  202. JButton button = new JButton("End Chat");
  203. JDialog dialog;
  204. String name;
  205. String[] contentArr;
  206. String port;
  207. String IP;
  208. /* static ArrayList <String> port_IP = new ArrayList <String>();
  209. String[] favContacts = {
  210. "BigKarlos",
  211. "lilVillz",
  212. "metaforMatte",
  213. "BirkoStoteles",
  214. "Övriga Kontakter!!"
  215.  
  216. };
  217. JComboBox contactList = new JComboBox(favContacts);
  218. JFileChooser contactChooser = new JFileChooser("/Users/kasperknudsen/Documents/Chatten");
  219. */
  220. public Client(String serverI,int contactP) {
  221.  
  222. setTitle("Client");
  223. serverIP = serverI;
  224. contactPort = contactP;
  225. userText = new JTextField();
  226. userText.setEditable(false);
  227. userText.addActionListener(
  228. new ActionListener() {
  229. public void actionPerformed(ActionEvent event) {
  230. sendMessage(event.getActionCommand());
  231. userText.setText("");
  232. }
  233. }
  234. );
  235.  
  236. add(userText, BorderLayout.NORTH);
  237. chatWindow = new JTextArea();
  238. add(new JScrollPane(chatWindow), BorderLayout.CENTER);
  239. setSize(800, 400);
  240. //add(contactList, BorderLayout.EAST);
  241.  
  242. add(button, BorderLayout.SOUTH);
  243. whenClickButton();
  244.  
  245.  
  246. setVisible(true);
  247. startRunning();
  248.  
  249. }
  250.  
  251. /* private ArrayList<String> readFile() {
  252. String arrayofContacts[] = {"/Users/kasperknudsen/Documents/Chatten/metaforMatte.txt", "/Users/kasperknudsen/Documents/Chatten/BigKarlos.txt", "/Users/kasperknudsen/Documents/Chatten/lillVillz.txt", "/Users/kasperknudsen/Documents/Chatten/BirkoStoteles.txt",};
  253.  
  254. ArrayList<String> content = new ArrayList<String>();
  255.  
  256. for (int i = 0; i < 4; i++) {
  257. File file = new File(arrayofContacts[i]);
  258. try {
  259. Scanner scannedFile = new Scanner(file);
  260. while (scannedFile.hasNext()) {
  261. content.add(scannedFile.next());
  262. }
  263. scannedFile.close();
  264.  
  265. } catch (IOException e) {
  266. e.printStackTrace();
  267. } finally {
  268.  
  269. }
  270.  
  271. }
  272.  
  273.  
  274. return content;
  275. }
  276.  
  277. private void comboBox() {
  278.  
  279. contactList.addActionListener(new ActionListener() {
  280. public void actionPerformed(ActionEvent e) {
  281.  
  282. contactList.addActionListener(this);
  283.  
  284. ArrayList<String> arrayList = readFile();
  285. contentArr = new String[arrayList.size()];
  286. arrayList.toArray(contentArr);
  287.  
  288.  
  289.  
  290. if (contactList.getSelectedIndex() == 0) {
  291. port = contentArr[4];
  292. IP = contentArr[5];
  293. }
  294. if (contactList.getSelectedIndex() == 1) {
  295. port = contentArr[7];
  296. IP = contentArr[8];
  297. }
  298. if (contactList.getSelectedIndex() == 2) {
  299. port = contentArr[1];
  300. IP = contentArr[2];
  301. }
  302. if (contactList.getSelectedIndex() == 3) {
  303. port = contentArr[10];
  304. IP = contentArr[11];
  305.  
  306. }
  307. if (contactList.getSelectedIndex() == 4) {
  308.  
  309. JFileChooser contactChooser = new JFileChooser("/Users/kasperknudsen/Documents/Chatten");
  310. contactChooser.getFileFilter();
  311. contactChooser.showOpenDialog(chatWindow);
  312. }
  313. returnPort_IP(IP,port);
  314.  
  315. }
  316.  
  317. });
  318.  
  319. }
  320.  
  321. private ArrayList <String> returnPort_IP(String IPAddress, String Portal) {
  322. port_IP = new ArrayList<String>();
  323. port_IP.add(IPAddress);
  324. port_IP.add(Portal);
  325.  
  326.  
  327. return port_IP;
  328. }
  329. */
  330. private void whenClickButton() {
  331. button.addActionListener(new ActionListener() {
  332. @Override
  333. public void actionPerformed(ActionEvent e) {
  334.  
  335. try {
  336. JOptionPane.showMessageDialog(chatWindow, "Disconnected from chat", "Inane error", JOptionPane.ERROR_MESSAGE);
  337.  
  338. } finally {
  339. System.exit(0);
  340. }
  341. }
  342. }
  343. );
  344. }
  345.  
  346. // Connect to the server
  347. void startRunning() {
  348. try {
  349. connectToServer();
  350. setUpStreams();
  351. whileChatting();
  352.  
  353. } catch (EOFException eofException) {
  354. showMessage("\n Client terminated the connection");
  355.  
  356. } catch (IOException ioException) {
  357. ioException.printStackTrace();
  358. } finally {
  359. closeCrap();
  360. System.exit(0);
  361. }
  362. }
  363.  
  364. //Connect to server
  365. private void connectToServer() throws IOException {
  366. showMessage("Attempting connection..\n");
  367. connection = new Socket(InetAddress.getByName("127.0.0.1"), 6666);
  368. showMessage("Connected to " + connection.getInetAddress().getHostName());
  369. System.out.println("HejConnecttoServer");
  370. }
  371.  
  372. //setup streams to send in messages
  373. private void setUpStreams() throws IOException {
  374. output = new ObjectOutputStream(connection.getOutputStream());
  375. output.flush();
  376. input = new ObjectInputStream(connection.getInputStream());
  377. showMessage("\n Your streams are now good to go \n");
  378. System.out.println("HejStreams");
  379. }
  380.  
  381. // While chatting with server
  382. private void whileChatting() throws IOException {
  383. ableToType(true);
  384. do {
  385. System.out.println("tråd1");
  386. try {
  387. message = (String) input.readObject();
  388. showMessage("\n" + message);
  389.  
  390. } catch (ClassNotFoundException classNotFoundException) {
  391. showMessage("\n I dont know that object type");
  392. }
  393.  
  394. } while (!message.equals("SERVER - END"));
  395.  
  396. }
  397.  
  398. private void closeCrap() {
  399. showMessage("\n Closing connection");
  400. ableToType(false);
  401. try {
  402. System.out.println("HejCloser");
  403. output.close();
  404. input.close();
  405. connection.close();
  406.  
  407. } catch (IOException ioException) {
  408. ioException.printStackTrace();
  409. }
  410. }
  411.  
  412. private void sendMessage(String message) {
  413. try {
  414. output.writeObject("CLIENT - " + message);
  415. output.flush();
  416. showMessage("\nCLIENT - " + message);
  417.  
  418. } catch (IOException ioException) {
  419. chatWindow.append("\n Something messed up in sending the message");
  420. }
  421. }
  422.  
  423. private void showMessage(final String message) {
  424. System.out.println("tråd");
  425. SwingUtilities.invokeLater(
  426. new Runnable() {
  427. public void run() {
  428. chatWindow.append(message);
  429. }
  430. }
  431. );
  432. }
  433.  
  434. private void ableToType(final boolean tof) { //tof = true or false
  435. System.out.println("tråd2");
  436. SwingUtilities.invokeLater(
  437. new Runnable() {
  438. public void run() {
  439. userText.setEditable(tof); //If true its editable. False it is not.
  440. }
  441. }
  442. );
  443. }
  444. // static ArrayList<String> getPort_IP() {
  445. // return port_IP;
  446.  
  447. // }
  448. }
  449.  
  450. class comboBoxClass {
  451. private JTextField field;
  452. private JTextArea window;
  453. String[] contentArr;
  454. String port;
  455. String IP;
  456. static ArrayList<String> port_IPP = new ArrayList<String>();
  457.  
  458. final JFrame frame = new JFrame("FavoritKontakter");
  459.  
  460. public comboBoxClass() {
  461.  
  462.  
  463.  
  464. String[] favContacts = {
  465. "BigKarlos",
  466. "lilVillz",
  467. "metaforMatte",
  468. "BirkoStoteles",
  469. "Övriga Kontakter!!"
  470.  
  471. };
  472. JComboBox contactList = new JComboBox(favContacts);
  473. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  474. frame.setSize(300, 100);
  475. Container cont = frame.getContentPane();
  476. cont.setLayout(new FlowLayout());
  477. cont.add(contactList);
  478. frame.setVisible(true);
  479.  
  480. contactList.addActionListener(
  481. new ActionListener() {
  482.  
  483. public void actionPerformed(ActionEvent e) {
  484. //contactList.addActionListener(this);
  485.  
  486. ArrayList<String> arrayList = readFile();
  487. contentArr = new String[arrayList.size()];
  488. arrayList.toArray(contentArr);
  489.  
  490.  
  491.  
  492. if (contactList.getSelectedIndex() == 0) {
  493. port = contentArr[4];
  494. IP = contentArr[5];
  495. }
  496. if (contactList.getSelectedIndex() == 1) {
  497. port = contentArr[7];
  498. IP = contentArr[8];
  499. }
  500. if (contactList.getSelectedIndex() == 2) {
  501. port = contentArr[1];
  502. IP = contentArr[2];
  503. }
  504. if (contactList.getSelectedIndex() == 3) {
  505. port = contentArr[10];
  506. IP = contentArr[11];
  507.  
  508. }
  509. if (contactList.getSelectedIndex() == 4) {
  510.  
  511. JFileChooser contactChooser = new JFileChooser("/Users/kasperknudsen/Documents/Chatten");
  512. contactChooser.getFileFilter();
  513. contactChooser.showOpenDialog(frame);
  514.  
  515.  
  516. }
  517.  
  518. frame.dispose();
  519. Client kontakt = new Client(IP,Integer.parseInt(port));
  520.  
  521. }
  522.  
  523. });
  524.  
  525.  
  526.  
  527. }
  528.  
  529. private ArrayList<String> readFile() {
  530.  
  531. String arrayofContacts[] = {"/Users/kasperknudsen/Documents/Chatten/metaforMatte.txt", "/Users/kasperknudsen/Documents/Chatten/BigKarlos.txt", "/Users/kasperknudsen/Documents/Chatten/lillVillz.txt", "/Users/kasperknudsen/Documents/Chatten/BirkoStoteles.txt",};
  532.  
  533. ArrayList<String> content = new ArrayList<String>();
  534.  
  535. for (int i = 0; i < 4; i++) {
  536. File file = new File(arrayofContacts[i]);
  537. try {
  538. Scanner scannedFile = new Scanner(file);
  539. while (scannedFile.hasNext()) {
  540. content.add(scannedFile.next());
  541. }
  542. scannedFile.close();
  543.  
  544. } catch (IOException e) {
  545. e.printStackTrace();
  546. } finally {
  547.  
  548. }
  549.  
  550. }
  551.  
  552.  
  553. return content;
  554. }
  555.  
  556. /* private void returnPort_IP(String IPAddress, String Portal) {
  557. port_IPP.add(IPAddress);
  558. port_IPP.add(Portal);
  559.  
  560. Client kontakt = new Client(port_IPP);
  561. System.exit(0);
  562. }*/
  563. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement