Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package labbserver;
- import java.io.*;
- import java.net.*;
- import java.awt.*;
- import java.awt.event.*;
- import java.nio.charset.StandardCharsets;
- import java.nio.file.*;
- import java.nio.file.Files;
- import java.nio.file.Paths;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Scanner;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- import javax.swing.*;
- import javax.swing.JDialog;
- import javax.swing.JFrame;
- public class LabbServer extends JFrame {
- public static void main(String[] args) {
- //boolean clientOrServer = true; //server runs if true
- boolean clientOrServer = false; // client runs if false
- if (clientOrServer) {
- LabbServer serverChat = new LabbServer();
- serverChat.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- serverChat.startRunning();
- } else {
- comboBoxClass box = new comboBoxClass();
- //Client clientChat = new Client(Client.getPort_IP());
- //clientChat.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- //clientChat.startRunning();
- }
- }
- private JTextField userText;
- private JTextArea chatWindow;
- private ObjectOutputStream output;
- private ObjectInputStream input;
- private Socket connection;
- private ServerSocket server;
- JButton button = new JButton("End Chat");
- static JDialog dialog;
- public LabbServer() {
- setTitle("Server");
- userText = new JTextField();
- userText.setEditable(false);
- userText.addActionListener(
- new ActionListener() {
- public void actionPerformed(ActionEvent event) {
- sendMessage(event.getActionCommand());
- userText.setText("");
- }
- }
- );
- add(userText, BorderLayout.NORTH);
- chatWindow = new JTextArea();
- add(new JScrollPane(chatWindow), BorderLayout.CENTER);
- setSize(800, 400);
- setVisible(true);
- add(button, BorderLayout.SOUTH);
- whenClickButton();
- }
- public void startRunning() {
- try {
- server = new ServerSocket(6666, 10); //6789 är port-numret, 10 personer kan connecta.
- waitForConnection();
- setUpStreams();
- whileChatting();
- } catch (EOFException eofException) {
- showMessage("\n Server ended the connection!");
- } catch (IOException ioException) {
- ioException.printStackTrace();
- } finally {
- closeCrap();
- System.exit(0);
- }
- }
- private void waitForConnection() throws IOException {
- showMessage("Waiting for someone to connect");
- connection = server.accept();
- showMessage("Now connected to " + connection.getInetAddress().getHostName());
- }
- private void setUpStreams() throws IOException {
- output = new ObjectOutputStream(connection.getOutputStream());
- output.flush();
- input = new ObjectInputStream(connection.getInputStream());
- showMessage("\n Streams are now setup! \n");
- }
- // While chatting with client
- private void whileChatting() throws IOException {
- String message = "You are now connected";
- sendMessage(message);
- ableToType(true);
- do {
- try {
- message = (String) input.readObject();
- showMessage("\n" + message);
- } catch (ClassNotFoundException classNotFoundException) {
- showMessage("\n I dont know that object type");
- }
- } while (!message.equals("CLIENT - END"));
- }
- //Close streams and sockets.
- private void closeCrap() {
- showMessage("\n Closing connection");
- ableToType(false);
- try {
- output.close();
- input.close();
- connection.close();
- } catch (IOException ioException) {
- ioException.printStackTrace();
- }
- }
- private void sendMessage(String message) {
- try {
- output.writeObject("SERVER - " + message); //output skickar medanden ut från servern.
- output.flush();
- showMessage("\nSERVER - " + message);
- } catch (IOException ioException) {
- chatWindow.append("\n Something messed up in sending the message");
- }
- }
- //Visar hela historiken i chaten, lägger till nya medelanden på skärmen hela tiden.
- private void showMessage(final String message) {
- SwingUtilities.invokeLater( //Uppdeterar hela tiden.
- new Runnable() {
- public void run() {
- chatWindow.append(message);
- }
- }
- );
- }
- private void ableToType(final boolean tof) { //tof = true or false
- SwingUtilities.invokeLater(
- new Runnable() {
- public void run() {
- userText.setEditable(tof); //If true its editable. False it is not.
- }
- }
- );
- }
- void whenClickButton() {
- button.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- System.exit(0);
- }
- }
- );
- }
- }
- /* Kasper Knudsen & Sara Särnblad STS 2A */
- class Client extends JFrame {
- private JTextField userText;
- private JTextArea chatWindow;
- private ObjectOutputStream output;
- private ObjectInputStream input;
- private String message = "";
- private Socket connection;
- int contactPort;
- String serverIP;
- int returnVal;
- JButton button = new JButton("End Chat");
- JDialog dialog;
- String name;
- String[] contentArr;
- String port;
- String IP;
- /* static ArrayList <String> port_IP = new ArrayList <String>();
- String[] favContacts = {
- "BigKarlos",
- "lilVillz",
- "metaforMatte",
- "BirkoStoteles",
- "Övriga Kontakter!!"
- };
- JComboBox contactList = new JComboBox(favContacts);
- JFileChooser contactChooser = new JFileChooser("/Users/kasperknudsen/Documents/Chatten");
- */
- public Client(String serverI,int contactP) {
- setTitle("Client");
- serverIP = serverI;
- contactPort = contactP;
- userText = new JTextField();
- userText.setEditable(false);
- userText.addActionListener(
- new ActionListener() {
- public void actionPerformed(ActionEvent event) {
- sendMessage(event.getActionCommand());
- userText.setText("");
- }
- }
- );
- add(userText, BorderLayout.NORTH);
- chatWindow = new JTextArea();
- add(new JScrollPane(chatWindow), BorderLayout.CENTER);
- setSize(800, 400);
- //add(contactList, BorderLayout.EAST);
- add(button, BorderLayout.SOUTH);
- whenClickButton();
- setVisible(true);
- startRunning();
- }
- /* private ArrayList<String> readFile() {
- 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",};
- ArrayList<String> content = new ArrayList<String>();
- for (int i = 0; i < 4; i++) {
- File file = new File(arrayofContacts[i]);
- try {
- Scanner scannedFile = new Scanner(file);
- while (scannedFile.hasNext()) {
- content.add(scannedFile.next());
- }
- scannedFile.close();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- }
- }
- return content;
- }
- private void comboBox() {
- contactList.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- contactList.addActionListener(this);
- ArrayList<String> arrayList = readFile();
- contentArr = new String[arrayList.size()];
- arrayList.toArray(contentArr);
- if (contactList.getSelectedIndex() == 0) {
- port = contentArr[4];
- IP = contentArr[5];
- }
- if (contactList.getSelectedIndex() == 1) {
- port = contentArr[7];
- IP = contentArr[8];
- }
- if (contactList.getSelectedIndex() == 2) {
- port = contentArr[1];
- IP = contentArr[2];
- }
- if (contactList.getSelectedIndex() == 3) {
- port = contentArr[10];
- IP = contentArr[11];
- }
- if (contactList.getSelectedIndex() == 4) {
- JFileChooser contactChooser = new JFileChooser("/Users/kasperknudsen/Documents/Chatten");
- contactChooser.getFileFilter();
- contactChooser.showOpenDialog(chatWindow);
- }
- returnPort_IP(IP,port);
- }
- });
- }
- private ArrayList <String> returnPort_IP(String IPAddress, String Portal) {
- port_IP = new ArrayList<String>();
- port_IP.add(IPAddress);
- port_IP.add(Portal);
- return port_IP;
- }
- */
- private void whenClickButton() {
- button.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- try {
- JOptionPane.showMessageDialog(chatWindow, "Disconnected from chat", "Inane error", JOptionPane.ERROR_MESSAGE);
- } finally {
- System.exit(0);
- }
- }
- }
- );
- }
- // Connect to the server
- void startRunning() {
- try {
- connectToServer();
- setUpStreams();
- whileChatting();
- } catch (EOFException eofException) {
- showMessage("\n Client terminated the connection");
- } catch (IOException ioException) {
- ioException.printStackTrace();
- } finally {
- closeCrap();
- System.exit(0);
- }
- }
- //Connect to server
- private void connectToServer() throws IOException {
- showMessage("Attempting connection..\n");
- connection = new Socket(InetAddress.getByName("127.0.0.1"), 6666);
- showMessage("Connected to " + connection.getInetAddress().getHostName());
- System.out.println("HejConnecttoServer");
- }
- //setup streams to send in messages
- private void setUpStreams() throws IOException {
- output = new ObjectOutputStream(connection.getOutputStream());
- output.flush();
- input = new ObjectInputStream(connection.getInputStream());
- showMessage("\n Your streams are now good to go \n");
- System.out.println("HejStreams");
- }
- // While chatting with server
- private void whileChatting() throws IOException {
- ableToType(true);
- do {
- System.out.println("tråd1");
- try {
- message = (String) input.readObject();
- showMessage("\n" + message);
- } catch (ClassNotFoundException classNotFoundException) {
- showMessage("\n I dont know that object type");
- }
- } while (!message.equals("SERVER - END"));
- }
- private void closeCrap() {
- showMessage("\n Closing connection");
- ableToType(false);
- try {
- System.out.println("HejCloser");
- output.close();
- input.close();
- connection.close();
- } catch (IOException ioException) {
- ioException.printStackTrace();
- }
- }
- private void sendMessage(String message) {
- try {
- output.writeObject("CLIENT - " + message);
- output.flush();
- showMessage("\nCLIENT - " + message);
- } catch (IOException ioException) {
- chatWindow.append("\n Something messed up in sending the message");
- }
- }
- private void showMessage(final String message) {
- System.out.println("tråd");
- SwingUtilities.invokeLater(
- new Runnable() {
- public void run() {
- chatWindow.append(message);
- }
- }
- );
- }
- private void ableToType(final boolean tof) { //tof = true or false
- System.out.println("tråd2");
- SwingUtilities.invokeLater(
- new Runnable() {
- public void run() {
- userText.setEditable(tof); //If true its editable. False it is not.
- }
- }
- );
- }
- // static ArrayList<String> getPort_IP() {
- // return port_IP;
- // }
- }
- class comboBoxClass {
- private JTextField field;
- private JTextArea window;
- String[] contentArr;
- String port;
- String IP;
- static ArrayList<String> port_IPP = new ArrayList<String>();
- final JFrame frame = new JFrame("FavoritKontakter");
- public comboBoxClass() {
- String[] favContacts = {
- "BigKarlos",
- "lilVillz",
- "metaforMatte",
- "BirkoStoteles",
- "Övriga Kontakter!!"
- };
- JComboBox contactList = new JComboBox(favContacts);
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.setSize(300, 100);
- Container cont = frame.getContentPane();
- cont.setLayout(new FlowLayout());
- cont.add(contactList);
- frame.setVisible(true);
- contactList.addActionListener(
- new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- //contactList.addActionListener(this);
- ArrayList<String> arrayList = readFile();
- contentArr = new String[arrayList.size()];
- arrayList.toArray(contentArr);
- if (contactList.getSelectedIndex() == 0) {
- port = contentArr[4];
- IP = contentArr[5];
- }
- if (contactList.getSelectedIndex() == 1) {
- port = contentArr[7];
- IP = contentArr[8];
- }
- if (contactList.getSelectedIndex() == 2) {
- port = contentArr[1];
- IP = contentArr[2];
- }
- if (contactList.getSelectedIndex() == 3) {
- port = contentArr[10];
- IP = contentArr[11];
- }
- if (contactList.getSelectedIndex() == 4) {
- JFileChooser contactChooser = new JFileChooser("/Users/kasperknudsen/Documents/Chatten");
- contactChooser.getFileFilter();
- contactChooser.showOpenDialog(frame);
- }
- frame.dispose();
- Client kontakt = new Client(IP,Integer.parseInt(port));
- }
- });
- }
- private ArrayList<String> readFile() {
- 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",};
- ArrayList<String> content = new ArrayList<String>();
- for (int i = 0; i < 4; i++) {
- File file = new File(arrayofContacts[i]);
- try {
- Scanner scannedFile = new Scanner(file);
- while (scannedFile.hasNext()) {
- content.add(scannedFile.next());
- }
- scannedFile.close();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- }
- }
- return content;
- }
- /* private void returnPort_IP(String IPAddress, String Portal) {
- port_IPP.add(IPAddress);
- port_IPP.add(Portal);
- Client kontakt = new Client(port_IPP);
- System.exit(0);
- }*/
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement