List of usage examples for java.net ServerSocket ServerSocket
public ServerSocket(int port) throws IOException
From source file:nr.co.blky.skype.proxy.SkypeProxy.java
public static void main(String[] args) throws Exception { if (!(args.length == 1 || args.length == 5)) { usage();// www .jav a 2 s . c o m return; } Skype.setDebug(false); Skype.setDeamon(false); String idTmp = "GESHA";//here is default Application-ID for all version. Application application = Skype.addApplication(idTmp); System.out.println("connected as listener for app [" + application + "]"); //par#0 String COMMAND = args[0]; /* * skypeproxy listen */ if (LISTEN.equals(COMMAND)) { // Shell will be available only on the __host__ ChatMessageListener shellTmp = new ShellOverChat(); Skype.addChatMessageListener(shellTmp); // PrintStream outTmp = System.out; TunnelServer tunnelServer = new TunnelServer(outTmp); application.addApplicationListener(tunnelServer); } else if (SEND.equals(COMMAND)) { /* * skypeproxy send <contact> <localport> <remotehost> <remoteport> */ String CONTACT = args[1]; int LOCALPORT = Integer.parseInt(args[2]); String HOST = args[3]; String PORT = args[4]; ServerSocket ss = new ServerSocket(LOCALPORT); while (true) { log.info("listening port " + LOCALPORT + "..."); // accept the connection from my client final Socket sc = ss.accept(); log.info("accepted conenction ..."); Friend toFriend = null; //search friend for (Friend next : application.getAllConnectableFriends()) { log.info("check for " + next.getId()); if (next.getId().equalsIgnoreCase(CONTACT)) { ; toFriend = next; break; } } log.info("forwarding to [" + CONTACT + "].."); final Stream skypeStream = application.connect(toFriend)[0]; // send initial message String SiD = "" + ((int) (Math.random() * Integer.MAX_VALUE)); skypeStream.send("" + TunnelServer.HOST + "=" + HOST + TunnelServer.EOL + TunnelServer.PORT + "=" + PORT + TunnelServer.EOL + TunnelServer.ID + "=" + SiD + TunnelServer.EOL + TunnelServer.LISTENHOST + "=" + "LOCALHOST" + TunnelServer.EOL); File traceFileTmp = new File("trace.log"); final PrintStream traceOut = new PrintStream(traceFileTmp); OutputStream outS = sc.getOutputStream(); InputStream inS = sc.getInputStream(); final SkypeRelay tc = new SkypeRelay(skypeStream, outS, inS, traceOut); tc.SiD = SiD; skypeStream.addStreamListener(tc); String stringFromTo = "*:" + LOCALPORT + "->" + CONTACT + "@" + HOST + ":" + PORT + " SiD:" + SiD + "//getID=" + skypeStream.getId(); final Thread relayTmp = new Thread(tc, stringFromTo); relayTmp.start(); log.debug("NEW TUNNEL localhost:" + LOCALPORT + " ->" + toFriend.getId() + "@" + HOST + ":" + PORT + " inited."); } } }
From source file:ChatServer.java
public static void main(String[] args) { // DeviceUpdater du = new DeviceUpdater(); int id = 0;// w w w . j a v a 2s . co m String host = "localhost"; int port = 11001; if (args.length == 2) { host = args[0]; port = Integer.valueOf(args[1]); } Socket sock; try { ServerSocket server = new ServerSocket(port); while (true) { // System.out.println("Server waiting for connects on port " + port); sock = server.accept(); id++; ChatServer threadOfServer = new ChatServer(sock, id); threadOfServer.start(); } } catch (Exception e) { e.printStackTrace(); } }
From source file:EchoClient.java
public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try {//from w w w.j a v a 2 s . c o m serverSocket = new ServerSocket(4444); } catch (IOException e) { System.err.println("Could not listen on port: 4444."); System.exit(1); } Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader( clientSocket.getInputStream())); String inputLine, outputLine; KnockKnockProtocol kkp = new KnockKnockProtocol(); outputLine = kkp.processInput(null); out.println(outputLine); while ((inputLine = in.readLine()) != null) { outputLine = kkp.processInput(inputLine); out.println(outputLine); if (outputLine.equals("Bye.")) break; } out.close(); in.close(); clientSocket.close(); serverSocket.close(); }
From source file:com.edduarte.protbox.Protbox.java
public static void main(String... args) { // activate debug / verbose mode if (args.length != 0) { List<String> argsList = Arrays.asList(args); if (argsList.contains("-v")) { Constants.verbose = true;/*ww w .j av a 2 s . co m*/ } } // use System's look and feel try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception ex) { // If the System's look and feel is not obtainable, continue execution with JRE look and feel } // check this is a single instance try { new ServerSocket(1882); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Another instance of Protbox is already running.\n" + "Please close the other instance first.", "Protbox already running", JOptionPane.ERROR_MESSAGE); System.exit(1); } // check if System Tray is supported by this operative system if (!SystemTray.isSupported()) { JOptionPane.showMessageDialog(null, "Your operative system does not support system tray functionality.\n" + "Please try running Protbox on another operative system.", "System tray not supported", JOptionPane.ERROR_MESSAGE); System.exit(1); } // add PKCS11 providers FileFilter fileFilter = new AndFileFilter(new WildcardFileFilter(Lists.newArrayList("*.config")), HiddenFileFilter.VISIBLE); File[] providersConfigFiles = new File(Constants.PROVIDERS_DIR).listFiles(fileFilter); if (providersConfigFiles != null) { for (File f : providersConfigFiles) { try { List<String> lines = FileUtils.readLines(f); String aliasLine = lines.stream().filter(line -> line.contains("alias")).findFirst().get(); lines.remove(aliasLine); String alias = aliasLine.split("=")[1].trim(); StringBuilder sb = new StringBuilder(); for (String s : lines) { sb.append(s); sb.append("\n"); } Provider p = new SunPKCS11(new ReaderInputStream(new StringReader(sb.toString()))); Security.addProvider(p); pkcs11Providers.put(p.getName(), alias); } catch (IOException | ProviderException ex) { if (ex.getMessage().equals("Initialization failed")) { ex.printStackTrace(); String s = "The following error occurred:\n" + ex.getCause().getMessage() + "\n\nIn addition, make sure you have " + "an available smart card reader connected before opening the application."; JTextArea textArea = new JTextArea(s); textArea.setColumns(60); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); textArea.setSize(textArea.getPreferredSize().width, 1); JOptionPane.showMessageDialog(null, textArea, "Error loading PKCS11 provider", JOptionPane.ERROR_MESSAGE); System.exit(1); } else { ex.printStackTrace(); JOptionPane.showMessageDialog(null, "Error while setting up PKCS11 provider from configuration file " + f.getName() + ".\n" + ex.getMessage(), "Error loading PKCS11 provider", JOptionPane.ERROR_MESSAGE); } } } } // adds a shutdown hook to save instantiated directories into files when the application is being closed Runtime.getRuntime().addShutdownHook(new Thread(Protbox::exit)); // get system tray and run tray applet tray = SystemTray.getSystemTray(); SwingUtilities.invokeLater(() -> { if (Constants.verbose) { logger.info("Starting application"); } //Start a new TrayApplet object trayApplet = TrayApplet.getInstance(); }); // prompts the user to choose which provider to use ProviderListWindow.showWindow(Protbox.pkcs11Providers.keySet(), providerName -> { // loads eID token eIDTokenLoadingWindow.showPrompt(providerName, (returnedUser, returnedCertificateData) -> { user = returnedUser; certificateData = returnedCertificateData; // gets a password to use on the saved registry files (for loading and saving) final AtomicReference<Consumer<SecretKey>> consumerHolder = new AtomicReference<>(null); consumerHolder.set(password -> { registriesPasswordKey = password; try { // if there are serialized files, load them if they can be decoded by this user's private key final List<SavedRegistry> serializedDirectories = new ArrayList<>(); if (Constants.verbose) { logger.info("Reading serialized registry files..."); } File[] registryFileList = new File(Constants.REGISTRIES_DIR).listFiles(); if (registryFileList != null) { for (File f : registryFileList) { if (f.isFile()) { byte[] data = FileUtils.readFileToByteArray(f); try { Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, registriesPasswordKey); byte[] registryDecryptedData = cipher.doFinal(data); serializedDirectories.add(new SavedRegistry(f, registryDecryptedData)); } catch (GeneralSecurityException ex) { if (Constants.verbose) { logger.info("Inserted Password does not correspond to " + f.getName()); } } } } } // if there were no serialized directories, show NewDirectory window to configure the first folder if (serializedDirectories.isEmpty() || registryFileList == null) { if (Constants.verbose) { logger.info("No registry files were found: running app as first time!"); } NewRegistryWindow.start(true); } else { // there were serialized directories loadRegistry(serializedDirectories); trayApplet.repaint(); showTrayApplet(); } } catch (AWTException | IOException | GeneralSecurityException | ReflectiveOperationException | ProtboxException ex) { JOptionPane.showMessageDialog(null, "The inserted password was invalid! Please try another one!", "Invalid password!", JOptionPane.ERROR_MESSAGE); insertPassword(consumerHolder.get()); } }); insertPassword(consumerHolder.get()); }); }); }
From source file:flink.iso8583.example.Server.java
public static void main(String[] args) throws Exception { mfact = ConfigParser.createFromClasspathConfig("flink/iso8583/example/config.xml"); log.info("Setting up server socket..."); ServerSocket server = new ServerSocket(9999); log.info("Waiting for connections..."); while (true) { Socket sock = server.accept(); log.info("New connection from " + sock.getInetAddress() + ":" + sock.getPort()); new Server(sock).start(); }//from w w w .j av a2s . c om }
From source file:j8583.example.Server.java
public static void main(String[] args) throws Exception { mfact = ConfigParser.createFromClasspathConfig("j8583/example/config.xml"); System.err.println("Setting up server socket..."); ServerSocket server = new ServerSocket(9999); System.err.println("Waiting for connections..."); while (true) { Socket sock = server.accept(); System.err.println(String.format("New connection from %s:%d", sock.getInetAddress(), sock.getPort())); new Thread(new Server(sock), "j8583-server").start(); }/*from w w w .jav a 2 s . co m*/ }
From source file:com.annuletconsulting.homecommand.server.HomeCommand.java
/** * This class will accept commands from a node in each room. For it to react to events on the server * computer, it must be also running as a node. However the server can cause all nodes to react * to an event happening on any node, such as an email or text arriving. A call on a node device * could pause all music devices, for example. * /* w w w . j ava2 s .c o m*/ * @param args */ public static void main(String[] args) { try { socket = Integer.parseInt(HomeComandProperties.getInstance().getServerPort()); nonJavaUserModulesPath = HomeComandProperties.getInstance().getNonJavaUserDir(); } catch (Exception exception) { System.out.println("Error loading from properties file."); exception.printStackTrace(); } try { sharedKey = HomeComandProperties.getInstance().getSharedKey(); if (sharedKey == null) System.out.println("shared_key is null, commands without valid signatures will be processed."); } catch (Exception exception) { System.out.println("shared_key not found in properties file."); exception.printStackTrace(); } try { if (args.length > 0) { String arg0 = args[0]; if (arg0.equals("help") || arg0.equals("?") || arg0.equals("usage") || arg0.equals("-help") || arg0.equals("-?")) { System.out.println( "The defaults can be changed by editing the HomeCommand.properties file, or you can override them temporarily using command line options."); System.out.println("\nHome Command Server command line overrride usage:"); System.out.println( "hcserver [server_port] [java_user_module_directory] [non_java_user_module_directory]"); //TODO make hcserver.sh System.out.println("\nDefaults:"); System.out.println("server_port: " + socket); System.out.println("java_user_module_directory: " + userModulesPath); System.out.println("non_java_user_module_directory: " + nonJavaUserModulesPath); System.out.println("\n2013 | Annulet, LLC"); } socket = Integer.parseInt(arg0); } if (args.length > 1) userModulesPath = args[1]; if (args.length > 2) nonJavaUserModulesPath = args[2]; System.out.println("Config loaded, initializing modules."); modules.add(new HueLightModule()); System.out.println("HueLightModule initialized."); modules.add(new QuestionModule()); System.out.println("QuestionModule initialized."); modules.add(new MathModule()); System.out.println("MathModule initialized."); modules.add(new MusicModule()); System.out.println("MusicModule initialized."); modules.add(new NonCopyrightInfringingGenericSpaceExplorationTVShowModule()); System.out.println("NonCopyrightInfringingGenericSpaceExplorationTVShowModule initialized."); modules.add(new HelpModule()); System.out.println("HelpModule initialized."); modules.add(new SetUpModule()); System.out.println("SetUpModule initialized."); modules.addAll(NonJavaUserModuleLoader.loadModulesAt(nonJavaUserModulesPath)); System.out.println("NonJavaUserModuleLoader initialized."); ServerSocket serverSocket = new ServerSocket(socket); System.out.println("Listening..."); while (!end) { Socket socket = serverSocket.accept(); InputStreamReader isr = new InputStreamReader(socket.getInputStream()); PrintWriter output = new PrintWriter(socket.getOutputStream(), true); int character; StringBuffer inputStrBuffer = new StringBuffer(); while ((character = isr.read()) != 13) { inputStrBuffer.append((char) character); } System.out.println(inputStrBuffer.toString()); String[] cmd; // = inputStrBuffer.toString().split(" "); String result = "YOUR REQUEST WAS NOT VALID JSON"; if (inputStrBuffer.substring(0, 1).equals("{")) { nodeType = extractElement(inputStrBuffer.toString(), "node_type"); if (sharedKey != null) { if (validateSignature(extractElement(inputStrBuffer.toString(), "time_stamp"), extractElement(inputStrBuffer.toString(), "signature"))) { if ("Y".equalsIgnoreCase(extractElement(inputStrBuffer.toString(), "cmd_encoded"))) cmd = decryptCommand(extractElement(inputStrBuffer.toString(), "command")); else cmd = extractElement(inputStrBuffer.toString(), "command").split(" "); result = getResult(cmd); } else result = "YOUR SIGNATURE DID NOT MATCH, CHECK SHARED KEY"; } else { cmd = extractElement(inputStrBuffer.toString(), "command").split(" "); result = getResult(cmd); } } System.out.println(result); output.print(result); output.print((char) 13); output.close(); isr.close(); socket.close(); } serverSocket.close(); System.out.println("Shutting down."); } catch (Exception exception) { exception.printStackTrace(); } }
From source file:ca.uqac.info.monitor.BeepBeepMonitor.java
public static void main(String[] args) { int verbosity = 1, slowdown = 0, tcp_port = 0; boolean show_stats = false, to_stdout = false; String trace_filename = "", pipe_filename = "", event_name = "message"; final MonitorFactory mf = new MonitorFactory(); // In case we open a socket ServerSocket m_serverSocket = null; Socket m_connection = null;// w ww .j a va 2 s . c o m // Parse command line arguments Options options = setupOptions(); CommandLine c_line = setupCommandLine(args, options); assert c_line != null; if (c_line.hasOption("verbosity")) { verbosity = Integer.parseInt(c_line.getOptionValue("verbosity")); } if (verbosity > 0) { showHeader(); } if (c_line.hasOption("version")) { System.err.println("(C) 2008-2013 Sylvain Hall et al., Universit du Qubec Chicoutimi"); System.err.println("This program comes with ABSOLUTELY NO WARRANTY."); System.err.println("This is a free software, and you are welcome to redistribute it"); System.err.println("under certain conditions. See the file COPYING for details.\n"); System.exit(ERR_OK); } if (c_line.hasOption("h")) { showUsage(options); System.exit(ERR_OK); } if (c_line.hasOption("version")) { System.exit(ERR_OK); } if (c_line.hasOption("slowdown")) { slowdown = Integer.parseInt(c_line.getOptionValue("slowdown")); if (verbosity > 0) System.err.println("Slowdown factor: " + slowdown + " ms"); } if (c_line.hasOption("stats")) { show_stats = true; } if (c_line.hasOption("csv")) { // Will output data in CSV format to stdout to_stdout = true; } if (c_line.hasOption("eventname")) { // Set event name event_name = c_line.getOptionValue("eventname"); } if (c_line.hasOption("t")) { // Read events from a trace trace_filename = c_line.getOptionValue("t"); } if (c_line.hasOption("p")) { // Read events from a pipe pipe_filename = c_line.getOptionValue("p"); } if (c_line.hasOption("k")) { // Read events from a TCP port tcp_port = Integer.parseInt(c_line.getOptionValue("k")); } if (!trace_filename.isEmpty() && !pipe_filename.isEmpty()) { System.err.println("ERROR: you must specify at most one of trace file or named pipe"); showUsage(options); System.exit(ERR_ARGUMENTS); } @SuppressWarnings("unchecked") List<String> remaining_args = c_line.getArgList(); if (remaining_args.isEmpty()) { System.err.println("ERROR: no input formula specified"); showUsage(options); System.exit(ERR_ARGUMENTS); } // Instantiate the event notifier boolean notify = (verbosity > 0); EventNotifier en = new EventNotifier(notify); en.m_slowdown = slowdown; en.m_csvToStdout = to_stdout; // Create one monitor for each input file and add it to the notifier for (String formula_filename : remaining_args) { try { String formula_contents = FileReadWrite.readFile(formula_filename); Operator op = Operator.parseFromString(formula_contents); op.accept(mf); Monitor mon = mf.getMonitor(); Map<String, String> metadata = getMetadata(formula_contents); metadata.put("Filename", formula_filename); en.addMonitor(mon, metadata); } catch (IOException e) { e.printStackTrace(); System.exit(ERR_IO); } catch (Operator.ParseException e) { System.err.println("Error parsing input formula"); System.exit(ERR_PARSE); } } // Read trace and iterate // Opens file PipeReader pr = null; try { if (!pipe_filename.isEmpty()) { // We tell the pipe reader we read a pipe File f = new File(pipe_filename); if (verbosity > 0) System.err.println("Reading from pipe named " + f.getName()); pr = new PipeReader(new FileInputStream(f), en, false); } else if (!trace_filename.isEmpty()) { // We tell the pipe reader we read a regular file File f = new File(trace_filename); if (verbosity > 0) System.err.println("Reading from file " + f.getName()); pr = new PipeReader(new FileInputStream(f), en, true); } else if (tcp_port > 0) { // We tell the pipe reader we read from a socket if (verbosity > 0) System.err.println("Reading from TCP port " + tcp_port); m_serverSocket = new ServerSocket(tcp_port); m_connection = m_serverSocket.accept(); pr = new PipeReader(m_connection.getInputStream(), en, false); } else { // We tell the pipe reader we read from standard input if (verbosity > 0) System.err.println("Reading from standard input"); pr = new PipeReader(System.in, en, false); } } catch (FileNotFoundException ex) { // We print both trace and pipe since one of them must be empty System.err.println("ERROR: file not found " + trace_filename + pipe_filename); System.exit(ERR_IO); } catch (IOException e) { // Caused by socket error e.printStackTrace(); System.exit(ERR_IO); } pr.setSeparator("<" + event_name + ">", "</" + event_name + ">"); // Check parameters for the event notifier if (c_line.hasOption("no-trigger")) { en.m_notifyOnVerdict = false; } else { en.m_notifyOnVerdict = true; } if (c_line.hasOption("mirror")) { en.m_mirrorEventsOnStdout = true; } // Start event notifier en.reset(); Thread th = new Thread(pr); long clock_start = System.nanoTime(); th.start(); try { th.join(); // Wait for thread to finish } catch (InterruptedException e1) { // Thread is finished } if (tcp_port > 0 && m_serverSocket != null) { // We opened a socket; now we close it try { m_serverSocket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } long clock_end = System.nanoTime(); int ret_code = pr.getReturnCode(); switch (ret_code) { case PipeReader.ERR_EOF: if (verbosity > 0) System.err.println("\nEnd of file reached"); break; case PipeReader.ERR_EOT: if (verbosity > 0) System.err.println("\nEOT received on pipe: closing"); break; case PipeReader.ERR_OK: // Do nothing break; default: // An error System.err.println("Runtime error"); System.exit(ERR_RUNTIME); break; } if (show_stats) { if (verbosity > 0) { System.out.println("Messages: " + en.m_numEvents); System.out.println("Time: " + (int) (en.m_totalTime / 1000000f) + " ms"); System.out.println("Clock time: " + (int) ((clock_end - clock_start) / 1000000f) + " ms"); System.out.println("Max heap: " + (int) (en.heapSize / 1048576f) + " MB"); } else { // If stats are asked but verbosity = 0, only show time value // (both monitor and wall clock) System.out.print((int) (en.m_totalTime / 1000000f)); System.out.print(","); System.out.print((int) ((clock_end - clock_start) / 1000000f)); } } System.exit(ERR_OK); }
From source file:EchoClient.java
public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; boolean listening = true; try {//from ww w .ja v a 2s.c o m serverSocket = new ServerSocket(4444); } catch (IOException e) { System.err.println("Could not listen on port: 4444."); System.exit(-1); } while (listening) new KKMultiServerThread(serverSocket.accept()).start(); serverSocket.close(); }
From source file:com.frostvoid.trekwar.server.TrekwarServer.java
public static void main(String[] args) { // load language try {/*from w w w . java 2 s . c om*/ lang = new Language(Language.ENGLISH); } catch (IOException ioe) { System.err.println("FATAL ERROR: Unable to load language file!"); System.exit(1); } System.out.println(lang.get("trekwar_server") + " " + VERSION); System.out.println("==============================================".substring(0, lang.get("trekwar_server").length() + 1 + VERSION.length())); // Handle parameters Options options = new Options(); options.addOption(OptionBuilder.withArgName("file").withLongOpt("galaxy").hasArg() .withDescription("the galaxy file to load").create("g")); //"g", "galaxy", true, "the galaxy file to load"); options.addOption(OptionBuilder.withArgName("port number").withLongOpt("port").hasArg() .withDescription("the port number to bind to (default 8472)").create("p")); options.addOption(OptionBuilder.withArgName("number").withLongOpt("save-interval").hasArg() .withDescription("how often (in turns) to save the galaxy to disk (default: 5)").create("s")); options.addOption(OptionBuilder.withArgName("log level").withLongOpt("log").hasArg() .withDescription("sets the log level: ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, OFF") .create("l")); options.addOption("h", "help", false, "prints this help message"); CommandLineParser cliParser = new BasicParser(); try { CommandLine cmd = cliParser.parse(options, args); String portStr = cmd.getOptionValue("p"); String galaxyFileStr = cmd.getOptionValue("g"); String saveIntervalStr = cmd.getOptionValue("s"); String logLevelStr = cmd.getOptionValue("l"); if (cmd.hasOption("h")) { HelpFormatter help = new HelpFormatter(); help.printHelp("TrekwarServer", options); System.exit(0); } if (cmd.hasOption("g") && galaxyFileStr != null) { galaxyFileName = galaxyFileStr; } else { throw new ParseException("galaxy file not specified"); } if (cmd.hasOption("p") && portStr != null) { port = Integer.parseInt(portStr); if (port < 1 || port > 65535) { throw new NumberFormatException(lang.get("port_number_out_of_range")); } } else { port = 8472; } if (cmd.hasOption("s") && saveIntervalStr != null) { saveInterval = Integer.parseInt(saveIntervalStr); if (saveInterval < 1 || saveInterval > 100) { throw new NumberFormatException("Save Interval out of range (1-100)"); } } else { saveInterval = 5; } if (cmd.hasOption("l") && logLevelStr != null) { if (logLevelStr.equalsIgnoreCase("finest")) { LOG.setLevel(Level.FINEST); } else if (logLevelStr.equalsIgnoreCase("finer")) { LOG.setLevel(Level.FINER); } else if (logLevelStr.equalsIgnoreCase("fine")) { LOG.setLevel(Level.FINE); } else if (logLevelStr.equalsIgnoreCase("config")) { LOG.setLevel(Level.CONFIG); } else if (logLevelStr.equalsIgnoreCase("info")) { LOG.setLevel(Level.INFO); } else if (logLevelStr.equalsIgnoreCase("warning")) { LOG.setLevel(Level.WARNING); } else if (logLevelStr.equalsIgnoreCase("severe")) { LOG.setLevel(Level.SEVERE); } else if (logLevelStr.equalsIgnoreCase("off")) { LOG.setLevel(Level.OFF); } else if (logLevelStr.equalsIgnoreCase("all")) { LOG.setLevel(Level.ALL); } else { System.err.println("ERROR: invalid log level: " + logLevelStr); System.err.println("Run again with -h flag to see valid log level values"); System.exit(1); } } else { LOG.setLevel(Level.INFO); } // INIT LOGGING try { LOG.setUseParentHandlers(false); initLogging(); } catch (IOException ex) { System.err.println("Unable to initialize logging to file"); System.err.println(ex); System.exit(1); } } catch (Exception ex) { System.err.println("ERROR: " + ex.getMessage()); System.err.println("use -h for help"); System.exit(1); } LOG.log(Level.INFO, "Trekwar2 server " + VERSION + " starting up"); // LOAD GALAXY File galaxyFile = new File(galaxyFileName); if (galaxyFile.exists()) { try { long timer = System.currentTimeMillis(); LOG.log(Level.INFO, "Loading galaxy file {0}", galaxyFileName); ObjectInputStream ois = new ObjectInputStream(new FileInputStream(galaxyFile)); galaxy = (Galaxy) ois.readObject(); timer = System.currentTimeMillis() - timer; LOG.log(Level.INFO, "Galaxy file loaded in {0} ms", timer); ois.close(); } catch (IOException ioe) { LOG.log(Level.SEVERE, "IO error while trying to load galaxy file", ioe); } catch (ClassNotFoundException cnfe) { LOG.log(Level.SEVERE, "Unable to find class while loading galaxy", cnfe); } } else { System.err.println("Error: file " + galaxyFileName + " not found"); System.exit(1); } // if turn == 0 (start of game), execute first turn to update fog of war. if (galaxy.getCurrentTurn() == 0) { TurnExecutor.executeTurn(galaxy); } LOG.log(Level.INFO, "Current turn : {0}", galaxy.getCurrentTurn()); LOG.log(Level.INFO, "Turn speed : {0} seconds", galaxy.getTurnSpeed() / 1000); LOG.log(Level.INFO, "Save Interval : {0}", saveInterval); LOG.log(Level.INFO, "Users / max : {0} / {1}", new Object[] { galaxy.getUserCount(), galaxy.getMaxUsers() }); // START SERVER try { server = new ServerSocket(port); LOG.log(Level.INFO, "Server listening on port {0}", port); } catch (BindException be) { LOG.log(Level.SEVERE, "Error: Unable to bind to port {0}", port); System.err.println(be); System.exit(1); } catch (IOException ioe) { LOG.log(Level.SEVERE, "Error: IO error while binding to port {0}", port); System.err.println(ioe); System.exit(1); } galaxy.startup(); Thread timerThread = new Thread(new Runnable() { @Override @SuppressWarnings("SleepWhileInLoop") public void run() { while (true) { try { Thread.sleep(1000); // && galaxy.getLoggedInUsers().size() > 0 will make server pause when nobody is logged in (TESTING) if (System.currentTimeMillis() > galaxy.nextTurnDate) { StringBuffer loggedInUsers = new StringBuffer(); for (User u : galaxy.getLoggedInUsers()) { loggedInUsers.append(u.getUsername()).append(", "); } long time = TurnExecutor.executeTurn(galaxy); LOG.log(Level.INFO, "Turn {0} executed in {1} ms", new Object[] { galaxy.getCurrentTurn(), time }); LOG.log(Level.INFO, "Logged in users: " + loggedInUsers.toString()); LOG.log(Level.INFO, "===================================================================================="); if (galaxy.getCurrentTurn() % saveInterval == 0) { saveGalaxy(); } galaxy.lastTurnDate = System.currentTimeMillis(); galaxy.nextTurnDate = galaxy.lastTurnDate + galaxy.turnSpeed; } } catch (InterruptedException e) { LOG.log(Level.SEVERE, "Error in main server loop, interrupted", e); } } } }); timerThread.start(); // ACCEPT CONNECTIONS AND DELEGATE TO CLIENT SESSIONS while (true) { Socket clientConnection; try { clientConnection = server.accept(); ClientSession c = new ClientSession(clientConnection, galaxy); Thread t = new Thread(c); t.start(); } catch (IOException ex) { LOG.log(Level.SEVERE, "IO Exception while trying to handle incoming client connection", ex); } } }