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);
 }
Esempio n. 2
1
 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();
 }
Esempio n. 3
1
  /**
   * 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();
    }
  }
Esempio n. 4
1
 @Override
 /** {@inheritDoc} */
 public Thread newThread(Runnable r) {
   Thread t = new Thread(r);
   t.setDaemon(true);
   return t;
 }
Esempio n. 5
1
 void start() {
   if (t == null) {
     t = new Thread(this, "UDP.OutgoingPacketHandler thread");
     t.setDaemon(true);
     t.start();
   }
 }
  @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");
    }
  }
Esempio n. 7
0
    @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);
      }
    }
Esempio n. 8
0
  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();
  }
Esempio n. 9
0
  /** 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
    //

  }
Esempio n. 10
0
  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();
    }
  }
Esempio n. 11
0
  /** 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");
    }
  }
Esempio n. 12
0
  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 void onDestroy() {
    running = false;
    if (scanThread != null) scanThread.interrupt();

    if (myWLocate != null) myWLocate.doPause();

    sensorManager.unregisterListener(
        this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER));

    if (scanData.getmView() != null) {
      ((WindowManager) getSystemService(WINDOW_SERVICE)).removeView(scanData.getmView());
      scanData.setmView(null);
    }
    try {
      if (wl != null) wl.release();
    } catch (RuntimeException re) {
    }
    wl = null;
    try {
      scanThread.join(1000);
    } catch (InterruptedException ie) {

    }
    System.exit(0);
  }
  public static void main(String args[]) {
    DatagramSocket skt = null;
    try {
      skt = new DatagramSocket(6789);
      byte[] buffer = new byte[1000];
      while (true) {
        DatagramPacket request = new DatagramPacket(buffer, buffer.length);
        skt.receive(request);
        System.out.println("Data received from client");
        System.out.println(new String(request.getData()));
        Thread.sleep(15000);

        String[] arrayMsg = (new String(request.getData())).split(" ");

        System.out.println(arrayMsg[0] + "server processed");

        byte[] sendMsg = (arrayMsg[0] + "server processed").getBytes();

        DatagramPacket reply =
            new DatagramPacket(sendMsg, sendMsg.length, request.getAddress(), request.getPort());

        System.out.println("sending data from server to client");
        Thread.sleep(15000);
        ;
        skt.send(reply);
      }
    } catch (Exception e) {

    }
  }
Esempio n. 15
0
 /** Stop listening on the server port. */
 public void shutdown() {
   if (listener != null) {
     Thread l = listener;
     listener = null;
     l.interrupt();
   }
 }
Esempio n. 16
0
  // Test the connected case to see if PUE is thrown
  public static void test2() throws Exception {

    setup();
    server.configureBlocking(true);
    server.connect(isa);
    server.configureBlocking(false);
    outBuf.rewind();
    server.write(outBuf);
    server.receive(inBuf);

    client.close();
    Thread.sleep(2000);
    outBuf.rewind();

    try {
      server.write(outBuf);
      Thread.sleep(2000);
      inBuf.clear();
      server.read(inBuf);
      if (onSolarisOrLinux()) throw new Exception("Expected PUE not thrown");
    } catch (PortUnreachableException pue) {
      System.err.println("received PUE");
    }
    server.close();
  }
Esempio n. 17
0
  /**
   * '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();
  }
 /** @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 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");
    }
  }
  // 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();
    }
  }
Esempio n. 21
0
 /** 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);
 }
Esempio n. 22
0
 /**
  * Get the current thread's context class loader which is set to the CommonClassLoader by
  * ApplicationServer
  *
  * @return the thread's context classloader if it exists; else the system class loader.
  */
 public static ClassLoader getClassLoader() {
   if (Thread.currentThread().getContextClassLoader() != null) {
     return Thread.currentThread().getContextClassLoader();
   } else {
     return ClassLoader.getSystemClassLoader();
   }
 }
Esempio n. 23
0
  /** Stops unicast and multicast receiver threads */
  void stopThreads() {
    Thread tmp;

    // 1. Stop the multicast receiver thread
    if (mcast_receiver != null) {
      if (mcast_receiver.isAlive()) {
        tmp = mcast_receiver;
        mcast_receiver = null;
        closeMulticastSocket(); // will cause the multicast thread to terminate
        tmp.interrupt();
        try {
          tmp.join(100);
        } catch (Exception e) {
        }
        tmp = null;
      }
      mcast_receiver = null;
    }

    // 2. Stop the unicast receiver thread
    if (ucast_receiver != null) {
      ucast_receiver.stop();
      ucast_receiver = null;
    }

    // 3. Stop the in_packet_handler thread
    if (incoming_packet_handler != null) {
      incoming_packet_handler.stop();
    }
  }
 /**
  * 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();
   }
 }
Esempio n. 25
0
  /*
   * Primary constructor, used to drive remainder of the test.
   *
   * Fork off the other side, then do your work.
   */
  JavaxHTTPSConnection() throws Exception {
    if (separateServerThread) {
      startServer(true);
      startClient(false);
    } else {
      startClient(true);
      startServer(false);
    }

    /*
     * Wait for other side to close down.
     */
    if (separateServerThread) {
      serverThread.join();
    } else {
      clientThread.join();
    }

    /*
     * When we get here, the test is pretty much over.
     *
     * If the main thread excepted, that propagates back
     * immediately.  If the other thread threw an exception, we
     * should report back.
     */
    if (serverException != null) {
      System.out.print("Server Exception:");
      throw serverException;
    }
    if (clientException != null) {
      System.out.print("Client Exception:");
      throw clientException;
    }
  }
  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();
  }
  /** Stops Jetty. */
  private void stopJetty() {
    // Jetty does not really stop the server if port is busy.
    try {
      if (httpSrv != null) {
        // If server was successfully started, deregister ports.
        if (httpSrv.isStarted()) ctx.ports().deregisterPorts(getClass());

        // Record current interrupted status of calling thread.
        boolean interrupted = Thread.interrupted();

        try {
          httpSrv.stop();
        } finally {
          // Reset interrupted flag on calling thread.
          if (interrupted) Thread.currentThread().interrupt();
        }
      }
    } catch (InterruptedException ignored) {
      if (log.isDebugEnabled()) log.debug("Thread has been interrupted.");

      Thread.currentThread().interrupt();
    } catch (Exception e) {
      U.error(log, "Failed to stop Jetty HTTP server.", e);
    }
  }
Esempio n. 28
0
  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 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;
  }
Esempio n. 30
0
 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();
   }
 }