初学socket(Server.java)

    技术2022-05-11  80

    /* * Server.java * * Created on 22 November 2006, 20:09 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ import java.io.*;import java.net.*;import java.util.*;import javax.swing.*;

    /** * The server for NewShop warehouse ordering * @author dsi06dh Dave Hollowell *  * @version 0.1 23rd November 2006 */public class Server {    // files for data    /**     * Branch filename - BranchFile.txt     */    private String branchFileName = File.separator + "BranchFile.txt";    /**     * Customer filename - CustomerFile.txt     */    private String customerFileName = File.separator + "CustomerFile.txt";    private String branchFile;    private String customerFile;    /**     * The directory structure for the files     */    private String directory;        // warehouse to use    /**     * Reference to the warehouse to use     */    private Warehouse wh;    /**     * Reference to the server socket in use     */    private ServerSocket serverSocket;    /**     * Reference to the display to use     */    private ServerGui display;    /**     * Is the server running     */    private boolean running = true;        /**     * default socket number     */    private static final int SOCKET_NO = 6999;        /**     * End of line character     */    private static final String NEWLINE = System.getProperty("line.separator");    /**     * Creates a new instance of Server     * @param port the port number for connections     */    public Server(int port)     {        // set look and feel        try         {            UIManager.setLookAndFeel(                UIManager.getSystemLookAndFeelClassName());        }         catch (Exception e)         {            try            {                UIManager.setLookAndFeel(                    UIManager.getCrossPlatformLookAndFeelClassName());                           }            catch (Exception ex)            {                // set look and feel exception                JFrame frame = new JFrame();                JOptionPane.showMessageDialog(frame,                    "Look and feel exception.",                    "System error - Server",                    JOptionPane.ERROR_MESSAGE);                                       }        }        // determine data file location        JFrame frame = new JFrame();        JFrame.setDefaultLookAndFeelDecorated(true);        JFileChooser fc = new JFileChooser();        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);        boolean valid;        // loop until selection is rejected or valid location for the files        do        {            valid = true;            int ret = fc.showDialog(frame, "Select the location of the data files");            // location chosen            if (ret == JFileChooser.APPROVE_OPTION)             {                directory = fc.getSelectedFile().toString();                branchFile = directory + branchFileName;                customerFile = directory + customerFileName;            }            // cancel selected            if (ret == JFileChooser.CANCEL_OPTION)                System.exit(1);            // check file exists            BufferedReader in = null;                    try            {                in = new BufferedReader                    (new FileReader(branchFile));                String temp = in.readLine();            }            catch (IOException e)            {                valid = false;            }            if (valid)            {                try                 {                    in.close();                }                 catch (IOException ex)                 {}                try                {                    in = new BufferedReader                        (new FileReader(branchFile));                    String temp = in.readLine();                }                catch (IOException e)                {                    valid = false;                }                if (valid)                {                    try                     {                        in.close();                    }                     catch (IOException ex)                     {                        valid = false;                    }                }                            }            if (!valid)            {                // file selection error                frame = new JFrame();                JOptionPane.showMessageDialog(frame,                    "Branch and customer files not found in the location "                         + "selected. Please try again" ,                    "File selection error - Server",                    JOptionPane.ERROR_MESSAGE);             }        }        while (!valid);                        display = new ServerGui();        display.statusMessage("Initialising warehouse." + NEWLINE);        wh = new Warehouse(branchFile, customerFile);        display.setWarehouse(wh);        display.statusMessage("Warehouse initialised." + NEWLINE);        String host = "unknown";        try         {            host = InetAddress.getLocalHost().toString();        }         catch (UnknownHostException ex)         {            display.statusMessage("Unknown host " + ex.getMessage() + NEWLINE);        }        String text = "Server: IP address " + host + NEWLINE +                "listening on port " + port + NEWLINE;        display.statusMessage(text);        try         {            serverSocket = new ServerSocket(port);        }         catch (IOException ex)         {            display.statusMessage("Failed to attach socket " + port + " " +                     ex.getMessage() + NEWLINE);        }    }        /**     * The main entry for the server     * @param args port number if different to the default     */    public static void main(String[] args)    {        int port = SOCKET_NO;        if (args.length > 0)            port = Integer.parseInt(args[0]);        Server server_1 = new Server(port);        server_1.process();    }        /**     * Creates threads to serve the incon=ming requests     */    private void process()    {        int client = 1;        display.statusMessage("waiting for client to connect" + NEWLINE);        while (running)        {            try             {                Socket socket = serverSocket.accept();                ServerThread w = new ServerThread(client++, socket,                         wh, display);                Thread t = new Thread(w);                t.start();            }             catch (IOException ex)             {                display.statusMessage("Communication failed " +                     ex.getMessage() + NEWLINE);            }        }    }} 


    最新回复(0)