// TcpServer.java SJ // Alkeellinen palvelin asiakassovellusten testaamiseen // Kukin uusi yhteys avaa uuden ikkunan jossa palvelimen komentoja voi // naputella asiakkaalle. // copy-pastattu omista TCP-esimerkeistä ja Java-tutorialin GUI esimerkeistä import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.net.*; import java.util.Scanner; import java.io.*; import java.lang.Thread; public class TcpServer { ServerSocket ss = null; public static void main(String[] args) { TcpServer p; if (args.length > 0) p = new TcpServer(Integer.valueOf(args[0])); else p = new TcpServer(); p.waitForConnections(); } // main() // konstruktorit avaavat yhteyden kuuntelulle public TcpServer(int portti) { try { ss = new ServerSocket(portti); System.out.println("Kuunnellaan porttia " + portti); } catch (Exception e) { System.err.println(e); ss = null; } } public TcpServer() { this(1234); } public void waitForConnections() { try { while (true) { // odotetaan uutta yhteyttä Socket cs = ss.accept(); // luodaan ja käynnistetää uusi palvelijasäie // new TcpServerForClient(cs).start(); new ConnectionThread(cs).start(); } } catch (Exception e) { System.err.println(e); ss = null; } } // kuuntele() private class ConnectionThread extends Thread { BufferedReader in = null; PrintWriter out = null; Socket cs = null; boolean stopped = false; TcpServerGUI gui = null; String title = "Connection"; public ConnectionThread(Socket s) { super(); cs = s; try { in = new BufferedReader(new InputStreamReader(cs.getInputStream())); out = new PrintWriter(cs.getOutputStream(), true); } catch (Exception e) { System.err.println(e); // TODO exit GUI // close socket } title = "TCPServer " + cs.getInetAddress() + ":" + cs.getPort(); gui = new TcpServerGUI(this); } private void createAndShowGUI() { //Create and set up the window. JFrame frame = new JFrame(title); // frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Add contents to the window. frame.add(gui); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent winEvent) { closeConnection(); } }); //Display the window. frame.pack(); frame.setVisible(true); } public void sendLine(String message) { try { out.println(message); } catch (Exception e) { System.err.println(e); // TODO exit GUI // close socket } } // called when window is closed public void closeConnection() { stopped = true; sendLine("Server Closing"); try { cs.close(); cs = null; } catch (Exception e) { System.err.println(e); // TODO exit GUI // close socket } } public void run() { // start GUI javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); try { while (true) { String rs = in.readLine(); if (rs == null) { gui.writeLine("Connection lost"); return; } rs = rs.trim(); if (rs.isEmpty()) continue; gui.writeLine(rs); } // while } catch (Exception e) { if (! stopped) { System.err.println(e); gui.writeLine(e.toString()); } } finally { try { cs.close(); } catch (Exception e2) {}; cs = null; gui.stop(); } } // run() } // class ConnectionThread // GUI for single user // skeleton code copied from Sun Java Tutorial private class TcpServerGUI extends JPanel implements ActionListener { protected JTextField textField; protected JTextArea textArea; ConnectionThread thread = null; boolean stopped = false; String client = "Client>"; public TcpServerGUI(ConnectionThread conn) { // Build GUI super(new GridBagLayout()); textField = new JTextField(50); textField.addActionListener(this); textArea = new JTextArea(15, 50); textArea.setEditable(false); JScrollPane scrollPane = new JScrollPane(textArea); //Add Components to this panel. GridBagConstraints c = new GridBagConstraints(); c.gridwidth = GridBagConstraints.REMAINDER; c.fill = GridBagConstraints.HORIZONTAL; add(textField, c); c.fill = GridBagConstraints.BOTH; c.weightx = 1.0; c.weighty = 1.0; add(scrollPane, c); thread = conn; } public void stop() { final String msg = "STOPPED\n"; stopped = true; SwingUtilities.invokeLater(new Runnable() { public void run() { textArea.append(msg); }}); } // called from another thread public void writeLine(String message) { final String msg = message; SwingUtilities.invokeLater(new Runnable() { public void run() { textArea.append(client + msg + "<\n"); }}); } public void actionPerformed(ActionEvent evt) { if (stopped) return; String text = textField.getText(); textArea.append("Server> " + text + "\n"); textField.selectAll(); //Make sure the new text is visible, even if there //was a selection in the text area. textArea.setCaretPosition(textArea.getDocument().getLength()); thread.sendLine(text); } } // class TcpServerGUI } // class TcpServer