|
| 1 | +import java.io.*; |
| 2 | +import java.net.*; |
| 3 | +import java.awt.*; |
| 4 | +import java.awt.event.*; |
| 5 | +import javax.swing.*; |
| 6 | + |
| 7 | +public class Server extends JFrame { |
| 8 | + |
| 9 | + private JTextField userText; |
| 10 | + private JTextArea chatWindow; |
| 11 | + private ObjectOutputStream output; |
| 12 | + private ObjectInputStream input; |
| 13 | + private ServerSocket server; |
| 14 | + private Socket connection; |
| 15 | + |
| 16 | + //constructor |
| 17 | + public Server(){ |
| 18 | + super("Buckys Instant Messenger"); |
| 19 | + userText = new JTextField(); |
| 20 | + userText.setEditable(false); |
| 21 | + userText.addActionListener( |
| 22 | + new ActionListener(){ |
| 23 | + public void actionPerformed(ActionEvent event){ |
| 24 | + sendMessage(event.getActionCommand()); |
| 25 | + userText.setText(""); |
| 26 | + } |
| 27 | + } |
| 28 | + ); |
| 29 | + add(userText, BorderLayout.NORTH); |
| 30 | + chatWindow = new JTextArea(); |
| 31 | + add(new JScrollPane(chatWindow)); |
| 32 | + setSize(300, 150); //Sets the window size |
| 33 | + setVisible(true); |
| 34 | + } |
| 35 | + |
| 36 | + public void startRunning(){ |
| 37 | + try{ |
| 38 | + server = new ServerSocket(6789, 100); //6789 is a dummy port for testing, this can be changed. The 100 is the maximum people waiting to connect. |
| 39 | + while(true){ |
| 40 | + try{ |
| 41 | + //Trying to connect and have conversation |
| 42 | + waitForConnection(); |
| 43 | + setupStreams(); |
| 44 | + whileChatting(); |
| 45 | + }catch(EOFException eofException){ |
| 46 | + showMessage("\n Server ended the connection! "); |
| 47 | + } finally{ |
| 48 | + closeCrap(); |
| 49 | + } |
| 50 | + } |
| 51 | + } catch (IOException ioException){ |
| 52 | + ioException.printStackTrace(); |
| 53 | + } |
| 54 | + } |
| 55 | + //wait for connection, then display connection information |
| 56 | + private void waitForConnection() throws IOException{ |
| 57 | + showMessage(" Waiting for someone to connect... \n"); |
| 58 | + connection = server.accept(); |
| 59 | + showMessage(" Now connected to " + connection.getInetAddress().getHostName()); |
| 60 | + } |
| 61 | + |
| 62 | +} |
0 commit comments