private final void socketrun() { do { if (link.socketport != 0) { try { Socket socket = new Socket(InetAddress.getByName(getCodeBase().getHost()), link.socketport); socket.setSoTimeout(30000); socket.setTcpNoDelay(true); link.s = socket; } catch (Exception _ex) { link.s = null; } link.socketport = 0; } if (link.runme != null) { Thread thread = new Thread(link.runme); thread.setDaemon(true); thread.start(); link.runme = null; } if (link.iplookup != null) { String s = "unknown"; try { s = InetAddress.getByName(link.iplookup).getHostName(); } catch (Exception _ex) { } link.host = s; link.iplookup = null; } try { Thread.sleep(100L); } catch (Exception _ex) { } } while (true); }
/** * Start this server. If we manage an own HttpServer, then the HttpServer will be started as well. */ public void start() { // URL as configured takes precedence String configUrl = NetworkUtil.replaceExpression(config.getJolokiaConfig().get(ConfigKey.DISCOVERY_AGENT_URL)); jolokiaHttpHandler.start( lazy, configUrl != null ? configUrl : url, config.getAuthenticator() != null); if (httpServer != null) { // Starting our own server in an own thread group with a fixed name // so that the cleanup thread can recognize it. ThreadGroup threadGroup = new ThreadGroup("jolokia"); threadGroup.setDaemon(false); Thread starterThread = new Thread( threadGroup, new Runnable() { @Override public void run() { httpServer.start(); } }); starterThread.start(); cleaner = new CleanupThread(httpServer, threadGroup); cleaner.start(); } }
private static void startSender() { Thread t = new Thread() { public void run() { try { DatagramChannel channel = DatagramChannel.open(); channel.configureBlocking(false); // channel.socket().connect(new InetSocketAddress(InetAddress.getLocalHost(), 1000)); ByteBuffer buffer = ByteBuffer.allocate(512 * 1000); byte[] buf; long time = JGN.getNanoTime(); for (int i = 0; i < 1000; i++) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); byte[] textBytes = ("Testing " + (i + 1)).getBytes(); dos.writeInt(textBytes.length); dos.write(textBytes); buf = baos.toByteArray(); baos.close(); buffer.clear(); buffer.put(buf); buffer.flip(); // channel.write(buffer); channel.send(buffer, new InetSocketAddress(InetAddress.getLocalHost(), 1000)); Thread.sleep(5); } System.out.println("Took " + ((JGN.getNanoTime() - time) / 1000000) + "ms to send."); } catch (Throwable t) { t.printStackTrace(); } } }; t.start(); }
void start() { if (t == null) { t = new Thread(this, "UDP.OutgoingPacketHandler thread"); t.setDaemon(true); t.start(); } }
/** @param args the command line arguments */ public static void main(String[] args) throws Exception { try { conf = new JsonFile("config.json").read(); address = conf.getJson().get("bind_IP").toString(); port = Integer.parseInt(conf.getJson().get("port").toString()); collection = new CollectThread(conf); collection.start(); s = new ServerSocket(port, 50, InetAddress.getByName(address)); System.out.print("(" + new GregorianCalendar().getTime() + ") -> "); System.out.print("listening on: " + address + ":" + port + "\n"); } catch (Exception e) { System.out.print("(" + new GregorianCalendar().getTime() + ") -> "); System.out.print("error: " + e); } while (true) { try { sock = s.accept(); System.out.print("(" + new GregorianCalendar().getTime() + ") -> "); System.out.print("connection from " + sock.getInetAddress() + ":"); System.out.print(sock.getPort() + "\n"); server = new ConsoleThread(conf, sock); server.start(); } catch (Exception e) { System.out.print("(" + new GregorianCalendar().getTime() + ") -> "); System.out.print("error: " + e); continue; } } }
public static void main(String[] args) throws Exception { if (args.length == 0) { System.err.println("Usage: java PortForward <local-port> <listen-port>"); return; } int localPort = Integer.parseInt(args[0]); int listenPort = Integer.parseInt(args[1]); ServerSocket ss = new ServerSocket(listenPort); final Socket in = ss.accept(); final Socket out = new Socket("127.0.0.1", localPort); Thread in2out = new Thread() { public void run() { try { InputStream i = in.getInputStream(); OutputStream o = out.getOutputStream(); int b = i.read(); while (b >= 0) { o.write((byte) b); b = i.read(); } o.close(); i.close(); } catch (Exception e) { e.printStackTrace(); } } }; in2out.start(); Thread out2in = new Thread() { public void run() { try { InputStream i = out.getInputStream(); OutputStream o = in.getOutputStream(); int b = i.read(); while (b >= 0) { o.write((byte) b); b = i.read(); } o.close(); i.close(); } catch (Exception e) { e.printStackTrace(); } } }; out2in.start(); in2out.join(); out2in.join(); in.close(); out.close(); }
public static void main(String[] args) throws Exception { int counter = 0; while (true) { Thread outThread = null; Thread errThread = null; try { // org.pitest.mutationtest.instrument.MutationTestUnit#runTestInSeperateProcessForMutationRange // *** start slave ServerSocket commSocket = new ServerSocket(0); int commPort = commSocket.getLocalPort(); System.out.println("commPort = " + commPort); // org.pitest.mutationtest.execute.MutationTestProcess#start // - org.pitest.util.CommunicationThread#start FutureTask<Integer> commFuture = createFuture(commSocket); // - org.pitest.util.WrappingProcess#start // - org.pitest.util.JavaProcess#launch Process slaveProcess = startSlaveProcess(commPort); outThread = new Thread(new ReadFromInputStream(slaveProcess.getInputStream()), "stdout"); errThread = new Thread(new ReadFromInputStream(slaveProcess.getErrorStream()), "stderr"); outThread.start(); errThread.start(); // *** wait for slave to die // org.pitest.mutationtest.execute.MutationTestProcess#waitToDie // - org.pitest.util.CommunicationThread#waitToFinish System.out.println("waitToFinish"); Integer controlReturned = commFuture.get(); System.out.println("controlReturned = " + controlReturned); // NOTE: the following won't get called if commFuture.get() fails! // - org.pitest.util.JavaProcess#destroy outThread.interrupt(); // org.pitest.util.AbstractMonitor#requestStop errThread.interrupt(); // org.pitest.util.AbstractMonitor#requestStop slaveProcess.destroy(); } catch (Exception e) { e.printStackTrace(System.out); } // test: the threads should exit eventually outThread.join(); errThread.join(); counter++; System.out.println("try " + counter + ": stdout and stderr threads exited normally"); } }
/** * Send a message to a specified address. * * @param message Pre-formatted message to send. * @param receiverAddress Address to send it to. * @param receiverPort Receiver port. * @throws IOException If there is a problem connecting or sending. */ public void sendMessage( byte message[], InetAddress receiverAddress, int receiverPort, boolean retry) throws IOException { if (message == null || receiverAddress == null) throw new IllegalArgumentException("Null argument"); SSLSocket sock = (SSLSocket) this.stack.ioHandler.sendBytes(receiverAddress, receiverPort, "TLS", message, retry); // // Created a new socket so close the old one and s // Check for null (bug fix sent in by Christophe) if (sock != mySock && sock != null) { try { if (mySock != null) mySock.close(); } catch (IOException ex) { /* ignore */ } mySock = sock; this.myClientInputStream = mySock.getInputStream(); this.myClientOutputStream = mySock.getOutputStream(); // start a new reader on this end of the pipe. Thread mythread = new Thread(this); mythread.setDaemon(true); mythread.setName("TLSMessageChannelThread"); mythread.start(); } }
// public static LinkedList<Message> queue = new LinkedList<Message>(); public static void main(String[] args) throws IOException { int port = 4444; ServerSocket serverSocket = null; try { String _port = System.getProperty("port"); if (_port != null) port = Integer.parseInt(_port); serverSocket = new ServerSocket(port); MBusQueueFactory.createQueues(); } catch (IOException e) { System.err.println("Could not listen on port: " + port + "."); System.exit(1); } System.out.println("Server is running at port : " + port + "."); Socket clientSocket = null; while (true) { try { System.out.println("Waiting for client....."); clientSocket = serverSocket.accept(); } catch (IOException e) { System.err.println("Accept failed."); e.printStackTrace(); } System.out.println(clientSocket.getInetAddress().toString() + " Connected"); Thread mt = new MessageBusWorker(clientSocket); mt.start(); } }
/** Default constructor. */ protected SIPTransactionStack() { super(); this.transactionTableSize = -1; // a set of methods that result in dialog creation. this.dialogCreatingMethods = new HashSet<String>(); // Standard set of methods that create dialogs. this.dialogCreatingMethods.add(Request.REFER); this.dialogCreatingMethods.add(Request.INVITE); this.dialogCreatingMethods.add(Request.SUBSCRIBE); // Notify may or may not create a dialog. This is handled in // the code. // Create the transaction collections clientTransactions = Collections.synchronizedList(new ArrayList<SIPClientTransaction>()); serverTransactions = Collections.synchronizedList(new ArrayList<SIPServerTransaction>()); // Dialog dable. this.dialogTable = new Hashtable<String, SIPDialog>(); clientTransactionTable = new Hashtable<String, SIPTransaction>(); serverTransactionTable = new Hashtable<String, SIPTransaction>(); // Start the timer event thread. this.timer = new Timer(); this.pendingRecordScanner = new Thread(new PendingRecordScanner(this)); this.pendingRecordScanner.setDaemon(true); this.pendingTransactions = new HashSet<SIPServerTransaction>(); pendingRecords = Collections.synchronizedList(new ArrayList<PendingRecord>()); pendingRecordScanner.setName("PendingRecordScanner"); pendingRecordScanner.start(); // endif // }
public static void main(String[] args) throws IOException { int queueLenth = 10; // number of clients that can connect at the same time int clientPort = 4500; // port that JokeClient and JokeServer communicate on Socket socketClient; // initialize joke and proverb databases Database joke = new JokeDatabase(); Database proverb = new ProverbDatabase(); System.out.println("Christian Loera's Joke server, listening at port 4500 and 4891.\n"); ServerAdmin servAdmin = new ServerAdmin(); // initialize ServerAdmin class Thread threadAdmin = new Thread(servAdmin); // create new thread of ServerAdmin class threadAdmin .start(); // start ServerAdmin thread to handle JokeClientAdmin connection asynchronously @SuppressWarnings("resource") ServerSocket clientServerSocket = new ServerSocket( clientPort, queueLenth); // creates socket that binds at port JokeClient connects to System.out.println("Client server is running"); while (true) { socketClient = clientServerSocket.accept(); // listening for JokeClient if (socketClient .isConnected()) // if socketClient connects to JokeClient execute new thread of Worker new Worker(socketClient, joke, proverb, mode).start(); } }
/** Test the http protocol handler with one WWW-Authenticate header with the value "NTLM". */ static void testNTLM() throws Exception { // server reply String reply = authReplyFor("NTLM"); System.out.println("===================================="); System.out.println("Expect client to fail with 401 Unauthorized"); System.out.println(reply); try (ServerSocket ss = new ServerSocket(0)) { Client client = new Client(ss.getLocalPort()); Thread thr = new Thread(client); thr.start(); // client ---- GET ---> server // client <--- 401 ---- client try (Socket s = ss.accept()) { new MessageHeader().parseHeader(s.getInputStream()); s.getOutputStream().write(reply.getBytes("US-ASCII")); } // the client should fail with 401 System.out.println("Waiting for client to terminate"); thr.join(); IOException ioe = client.ioException(); if (ioe != null) System.out.println("Client failed: " + ioe); int respCode = client.respCode(); if (respCode != 0 && respCode != -1) System.out.println("Client received HTTP response code: " + respCode); if (respCode != HttpURLConnection.HTTP_UNAUTHORIZED) throw new RuntimeException("Unexpected response code"); } }
public static void main(String[] args) throws IOException { Map<String, String> cache = new HashMap<String, String>(); File fileName = new File("."); File[] fileList = fileName.listFiles(); for (int i = 0; i < 16; i++) { if (fileList[i].getName().contains("test") && !fileList[i].isDirectory()) { cache.put(fileList[i].getName(), new Scanner(fileList[i]).next()); } } try { ServerSocket listener = new ServerSocket(8889); Socket server; while (true) { // perhaps replace true with a variable doComms connection; /* * see slides 9 number 29 and implement that for the file * generator */ server = listener.accept(); // PrintStream out = new PrintStream(server.getOutputStream()); // out.println("Arch Linus Rocks!"); // out.flush(); doComms conn_c = new doComms(server, cache); Thread t = new Thread(conn_c); t.start(); } } catch (IOException ioe) { // replace this with call to logging thread System.out.println("IOException on socket listen: " + ioe); ioe.printStackTrace(); } }
public static void startServer() { try { System.out.println("Starting server..."); serverSocket = new ServerSocket(7788); System.out.println("Server Started... Address: " + serverSocket.getInetAddress()); while (true) { socket = serverSocket.accept(); for (int i = 0; i < 10; i++) { if (user[i] == null) { System.out.println("User " + (i + 1) + " connected from " + socket.getInetAddress()); socket.setTcpNoDelay(false); out = new ObjectOutputStream(socket.getOutputStream()); in = new ObjectInputStream(socket.getInputStream()); out.writeInt(i); out.flush(); User theUser = new User(out, in, i); user[i] = theUser; Thread thread = new Thread(user[i]); thread.start(); break; } } } } catch (IOException e) { e.printStackTrace(); } }
public void disconnect(String name, I_InfoPlayer player) { try { Naming.unbind("rmi://" + serverInfo.getIpAddr() + ":1099/I_InfoGame"); Naming.unbind("rmi://" + serverInfo.getIpAddr() + ":1099/" + name); } catch (Exception e) { System.out.println("Failed unbind"); System.exit(128); } System.out.println("Disconnected"); ServerTimer timer = new ServerTimer(5); Thread thread = new Thread(timer); thread.start(); while (!timer.finished()) ; timer.shutDown(); timer = null; System.gc(); try { Naming.rebind("rmi://" + serverAddress + ":1099/I_InfoGame", game); Naming.rebind("rmi://" + serverAddress + ":1099/" + name, player); } catch (Exception e) { System.out.println("Failed rebind"); System.exit(128); } System.out.println("Reconnected"); }
public void run() throws IOException { ServerSocket server = new ServerSocket(this.portNumber); this.socket = server.accept(); this.socket.setTcpNoDelay(true); server.close(); DataInputStream in = new DataInputStream(this.socket.getInputStream()); final DataOutputStream out = new DataOutputStream(this.socket.getOutputStream()); while (true) { final String className = in.readUTF(); Thread thread = new Thread() { public void run() { try { loadAndRun(className); out.writeBoolean(true); System.err.println(VerifyTests.class.getName()); System.out.println(VerifyTests.class.getName()); } catch (Throwable e) { e.printStackTrace(); try { System.err.println(VerifyTests.class.getName()); System.out.println(VerifyTests.class.getName()); out.writeBoolean(false); } catch (IOException e1) { // ignore } } } }; thread.start(); } }
public void connectAndFormStreams() throws Exception { serverSocket = new ServerSocket(); serverSocket.setReuseAddress(true); serverSocket.bind(new InetSocketAddress(listeningPortNumber)); while (!Thread.interrupted()) { Log.i("Connect", "Before accept()"); s = serverSocket.accept(); Log.i("Connect", "after accept"); is = s.getInputStream(); InputStreamReader isr = new InputStreamReader(is); br = new BufferedReader(isr); Thread serverThread = new Thread(this); serverThread.start(); } s.close(); serverSocket.close(); }
public boolean request(Object soaprequest) { if (!checkSoapMemberVariable()) return false; ServiceRequest req = new ServiceRequest( this.ServerUrl, this.SoapAction, this.NameSpace, this.MethodName, this.SoapVersion, this.DotNet, (SoapObject) soaprequest); Thread thread = new Thread(req); try { thread.start(); thread.join(); } catch (Exception e) { this.Response = null; e.printStackTrace(); return false; } this.Response = req.getResponse(); if (this.Response == null) return false; return true; }
void startServer(boolean newThread) throws Exception { if (newThread) { serverThread = new Thread() { public void run() { try { doServerSide(); } catch (Exception e) { /* * Our server thread just died. * * Release the client, if not active already... */ System.err.println("Server died..."); System.err.println(e); serverReady = true; serverException = e; } } }; serverThread.start(); } else { doServerSide(); } }
/** Called by ImageJ when the user selects Quit. */ public void quit() { quitMacro = IJ.macroRunning(); Thread thread = new Thread(this, "Quit"); thread.setPriority(Thread.NORM_PRIORITY); thread.start(); IJ.wait(10); }
@Override public void run() { // Wait for clients to connect. // When a client has connected, create a new ClientConnection Socket clientSock = null; channel.startServer(); while (true) { clientSock = channel.accept(); System.out.println("A new client has connected"); if (clientSock != null) { ClientConnection clientConn = new ClientConnection(clientSock, this, nextClientID); nextClientID++; Thread thread = new Thread(clientConn); thread.start(); clientSock = null; } System.out.println( "Client has been served by ClientHandler. " + "Now looking for new connections"); } }
@Override public void actionPerformed(ActionEvent e) { Frame frame = getFrame(); JFileChooser chooser = new JFileChooser(); int ret = chooser.showOpenDialog(frame); if (ret != JFileChooser.APPROVE_OPTION) { return; } File f = chooser.getSelectedFile(); if (f.isFile() && f.canRead()) { Document oldDoc = getEditor().getDocument(); if (oldDoc != null) { oldDoc.removeUndoableEditListener(undoHandler); } if (elementTreePanel != null) { elementTreePanel.setEditor(null); } getEditor().setDocument(new PlainDocument()); frame.setTitle(f.getName()); Thread loader = new FileLoader(f, editor.getDocument()); loader.start(); } else { JOptionPane.showMessageDialog( getFrame(), "Could not open file: " + f, "Error opening file", JOptionPane.ERROR_MESSAGE); } }
public SetIfModifiedSince() throws Exception { serverSock = new ServerSocket(0); int port = serverSock.getLocalPort(); Thread thr = new Thread(this); thr.start(); Date date = new Date(new Date().getTime() - 1440000); // this time yesterday URL url; HttpURLConnection con; // url = new URL(args[0]); url = new URL("http://localhost:" + String.valueOf(port) + "/anything"); con = (HttpURLConnection) url.openConnection(); con.setIfModifiedSince(date.getTime()); con.connect(); int ret = con.getResponseCode(); if (ret == 304) { System.out.println("Success!"); } else { throw new RuntimeException( "Test failed! Http return code using setIfModified method is:" + ret + "\nNOTE:some web servers are not implemented according to RFC, thus a failed test does not necessarily indicate a bug in setIfModifiedSince method"); } }
private void startListening() { // if listener thread is alive and listening now, no need to recreate. Just reuse it. if (listenerThread != null && listenerThread.isAlive()) { return; } Runnable listeningAction = () -> { boolean running = true; while (connected && running) { List<String> list = getMessages(); localHistory.addAll(list); try { Thread.sleep(POLLING_PERIOD_MILLIS); } catch (InterruptedException e) { logger.error("The message listening thread was interrupted", e); running = false; } } }; listenerThread = new Thread(listeningAction); listenerThread.start(); }
/** * 'handler' can be of any type that implements 'exportedInterface', but only methods declared by * the interface (and its superinterfaces) will be invocable. */ public <T> InAppServer( String name, String portFilename, InetAddress inetAddress, Class<T> exportedInterface, T handler) { this.fullName = name + "Server"; this.exportedInterface = exportedInterface; this.handler = handler; // In the absence of authentication, we shouldn't risk starting a server as root. if (System.getProperty("user.name").equals("root")) { Log.warn( "InAppServer: refusing to start unauthenticated server \"" + fullName + "\" as root!"); return; } try { File portFile = FileUtilities.fileFromString(portFilename); secretFile = new File(portFile.getPath() + ".secret"); Thread serverThread = new Thread(new ConnectionAccepter(portFile, inetAddress), fullName); // If there are no other threads left, the InApp server shouldn't keep us alive. serverThread.setDaemon(true); serverThread.start(); } catch (Throwable th) { Log.warn("InAppServer: couldn't start \"" + fullName + "\".", th); } writeNewSecret(); }
private void startReceiver() { if (receiver == null || !receiver.isAlive()) { receiver = new Thread(Util.getGlobalThreadGroup(), this, "ReceiverThread"); receiver.setDaemon(true); receiver.start(); if (log.isTraceEnabled()) log.trace("receiver thread started"); } }
private void RunAllQueriesBtnMouseClicked( java.awt.event.MouseEvent evt) { // GEN-FIRST:event_RunAllQueriesBtnMouseClicked // TODO add your handling code here: qThread = new PBVCPluginQueryThread(this, "", queryList, owlModel); Thread qthr = new Thread(qThread); qthr.start(); } // GEN-LAST:event_RunAllQueriesBtnMouseClicked
/** Start the network listening thread. */ void start() { this.running = true; Thread thread = new Thread(this, "IceConnector@" + hashCode()); thread.setDaemon(true); thread.start(); }
public void start() { if (thread == null) { thread = new Thread(this, "UDP.UcastReceiverThread"); thread.setDaemon(true); running = true; thread.start(); } }
void start() { logger.log(Level.FINEST, "Starting TCP node"); please_stop = false; node_thread = new SelectThread(); node_thread.setDaemon(true); node_thread.start(); logger.log(Level.FINEST, "Started TCP node"); }