ServerFrame.java


import java.awt.*;
import java.awt.font.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.*;

public class ServerFrame {
    public static int thread_count=0;
    public static String dialog="";
    public static java.util.List<ChatThread> chat_list= new java.util.ArrayList<>();
    public static void main(String args[]) {
        try {
            JTextArea theTextArea=new JTextArea(5,40);
            Font the_font = new Font("SansSerif", Font.BOLD, 20);
            theTextArea.setFont(the_font);
            JFrame frame = new JFrame("Chat Server Frame");
            JButton button = new JButton("Request Port");
            button.addActionListener((ev)->{try_port(theTextArea);});
            Container contentPane = frame.getContentPane();
            contentPane.add(theTextArea, BorderLayout.CENTER);
            contentPane.add(button, BorderLayout.SOUTH);
            frame.setSize(500, 200);
            frame.setVisible(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ;
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }
    public static void try_port(JTextArea aTextArea){
        ServerSocket server;
        int portnumber=Integer.parseInt(aTextArea.getText().trim());
        try {
            server = new ServerSocket(portnumber);
        } catch (Exception e) {
            ServerFrame.dialog=ServerFrame.dialog+"\nPort "+aTextArea.getText().trim()+ " may already be in use.";
            aTextArea.setText(ServerFrame.dialog);
            aTextArea.repaint();
            return;
        }
        ChatThread chat = new ChatThread(server); //one per port
        chat_list.add(chat);
        chat_list.get(thread_count).start();
        thread_count++;
        ServerFrame.dialog=ServerFrame.dialog+"\nPort "+aTextArea.getText().trim()+ " is open and listening.";
        aTextArea.setText(ServerFrame.dialog);
        aTextArea.repaint();
        return;
    }

    public static void broadcast(String s){
        for (int i=0;i<thread_count;i++) {
            chat_list.get(i).out.println(s);
            chat_list.get(i).out.flush();
        }
    }
}