import java.net.ServerSocket; import java.net.Socket; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.io.PrintWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.JButton; class ClientConnection { private static ArrayList allClients = new ArrayList(); private final Socket socket; private final PrintWriter out; public ClientConnection(Socket s) throws IOException { socket = s; out = new PrintWriter( new BufferedWriter( new OutputStreamWriter( socket.getOutputStream())), true); System.out.println("En klienttråd har skapats."); allClients.add(this); } public static void sendToAllClients(String line) { Iterator i = allClients.iterator(); while (i.hasNext()) { ClientConnection t = (ClientConnection)i.next(); t.out.println(line); } } } // class ClientConnection public class GrafiskServer { public static final int PORT = 3003; public static void main(String[] args) throws IOException { JFrame frame = new JFrame("GrafiskServer"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container cp = frame.getContentPane(); cp.setLayout(new FlowLayout()); final JTextField textfield = new JTextField("Kilpisjärvi -41"); JButton button = new JButton("Skicka"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String inline = textfield.getText(); System.out.println("Du sa '" + inline + "'"); ClientConnection.sendToAllClients(inline); } }); cp.add(textfield); cp.add(button); frame.pack(); frame.setVisible(true); ServerSocket s = new ServerSocket(PORT); System.out.println("Server-socketen: " + s); System.out.println("Servern lyssnar..."); try { while(true) { // Blocks until a connection occurs: Socket socket = s.accept(); System.out.println("Uppkoppling accepterad."); System.out.println("Den nya socketen: " + socket); try { ClientConnection cc = new ClientConnection(socket); System.out.println("Ny klientkoppling skapad."); System.out.println("Den nya klientkopplingen: " + cc); } catch(IOException e) { // If the constructor fails, close the socket, // otherwise the thread will close it: socket.close(); } } } finally { s.close(); } } // main } // GrafiskServer