Esempio n. 1
0
  public ConnectFourServer() {
    JTextArea jtaLog = new JTextArea();

    // Create a scroll pane to hold text area
    JScrollPane scrollPane = new JScrollPane(jtaLog);

    // Add the scroll pane to the frame
    add(scrollPane, BorderLayout.CENTER);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(300, 300);
    setTitle("TicTacToeServer");
    setVisible(true);

    try {
      // Create a server socket
      ServerSocket serverSocket = new ServerSocket(8000);
      jtaLog.append(new Date() + ": Server started at socket 8000\n");

      // Number a session
      int sessionNo = 1;

      // Ready to create a session for every two players
      while (true) {
        jtaLog.append(new Date() + ": Wait for players to join session " + sessionNo + '\n');

        // Connect to player 1
        Socket player1 = serverSocket.accept();

        jtaLog.append(new Date() + ": Player 1 joined session " + sessionNo + '\n');
        jtaLog.append("Player 1's IP address" + player1.getInetAddress().getHostAddress() + '\n');

        // Notify that the player is Player 1
        new DataOutputStream(player1.getOutputStream()).writeInt(PLAYER1);

        // Connect to player 2
        Socket player2 = serverSocket.accept();

        jtaLog.append(new Date() + ": Player 2 joined session " + sessionNo + '\n');
        jtaLog.append("Player 2's IP address" + player2.getInetAddress().getHostAddress() + '\n');

        // Notify that the player is Player 2
        new DataOutputStream(player2.getOutputStream()).writeInt(PLAYER2);

        // Display this session and increment session number
        jtaLog.append(new Date() + ": Start a thread for session " + sessionNo++ + '\n');

        // Create a new thread for this session of two players
        HandleASession task = new HandleASession(player1, player2);

        // Start the new thread
        new Thread(task).start();
      }
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
Esempio n. 2
0
 /** Listens for client requests until stopped. */
 public void run() {
   try {
     while (listener != null) {
       try {
         Socket socket = serverSocket.accept();
         if (!paranoid || checkSocket(socket)) {
           Runner runner = getRunner();
           runner.handle(socket);
           // new Connection (socket);
         } else socket.close();
       } catch (Exception ex) {
         System.err.println("Exception in XML-RPC listener loop (" + ex + ").");
       } catch (Error err) {
         System.err.println("Error in XML-RPC listener loop (" + err + ").");
       }
     }
   } catch (Exception exception) {
     System.err.println("Error accepting XML-RPC connections (" + exception + ").");
   } finally {
     System.err.println("Closing XML-RPC server socket.");
     try {
       serverSocket.close();
       serverSocket = null;
     } catch (IOException ignore) {
     }
   }
 }
 /**
  * creates a server socket listening on the port specified in the parameter of the constructor,
  * and waits for a single incoming client connection which it handles by invoking the <CODE>
  * addNewClientConnection(s)</CODE> method of the enclosing server, and then the thread exits.
  */
 public void run() {
   try {
     ServerSocket ss = new ServerSocket(_port);
     System.out.println("Srv: Now Accepting Single Client Connection");
     // while (true) {
     try {
       Socket s = ss.accept();
       System.out.println("Srv: Client Added to the Network");
       addNewClientConnection(s);
       System.out.println("Srv: finished adding client connection");
     } catch (Exception e) {
       // e.printStackTrace();
       System.err.println("Client Connection failed, exiting...");
       System.exit(-1);
     }
     // }
   } catch (IOException e) {
     // e.printStackTrace();
     utils.Messenger.getInstance()
         .msg(
             "PDBTExecSingleCltWrkInitSrv.C2Thread.run(): "
                 + "Failed to create Server Socket, Server exiting.",
             0);
     System.exit(-1);
   }
 }
Esempio n. 4
0
  static void fun() {
    PrintStream toSoc;

    try {
      ServerSocket f = new ServerSocket(9090);
      while (true) {
        Socket t = f.accept();
        BufferedReader fromSoc = new BufferedReader(new InputStreamReader(t.getInputStream()));
        String video = fromSoc.readLine();
        System.out.println(video);
        searcher obj = new searcher();
        boolean fs;
        fs = obj.search(video);
        if (fs == true) {
          System.out.println("stream will starts");
          toSoc = new PrintStream(t.getOutputStream());
          toSoc.println("stream starts");

        } else {
          toSoc = new PrintStream(t.getOutputStream());
          toSoc.println("sorry");
        }
      }

    } catch (Exception e) {
      System.out.println(e);
    }
  }
  /** Creates the server. */
  public static void main(String args[]) {
    client = null;
    ServerSocket server = null;

    try {
      System.out.print("\nCreating Server...\n");
      // creates the server
      server = new ServerSocket(8008);
      System.out.print("Created\n");
      // get the ip Address and the host name.
      InetAddress localAddr = InetAddress.getLocalHost();
      System.out.println("IP address: " + localAddr.getHostAddress());
      System.out.println("Hostname: " + localAddr.getHostName());

    } catch (IOException e) {
      // sends a
      System.out.println("IO" + e);
    }

    // constantly checks for a new aocket trying to attach itself to the trhead
    while (true) {
      try {
        client = server.accept();
        // create a new thread.
        FinalMultiThread thr = new FinalMultiThread(client);
        System.out.print(client.getInetAddress() + " : " + thr.getUserName() + "\n");
        CliList.add(thr);
        current++;
        thr.start();
      } catch (IOException e) {
        System.out.println(e);
      }
    }
  }
Esempio n. 6
0
  public static void main(String args[]) {
    String fileToSend = "C:\\test1.txt";
    while (true) {
      // Maak lokale variabels eerst aan.
      // Dit is nodig om deze ook te gebruiken buiten de "try catch" blok.
      ServerSocket welcomeSocket = null;
      Socket connectionSocket = null;
      BufferedOutputStream outToClient = null;

      try {
        // poort waar gebruiker kan op connecteren
        welcomeSocket = new ServerSocket(3248);
        // Tot er een gebruiker gevonden is zal .accept() blijven wachten
        // Nadat er iemand geconnecteerd is zal er een nieuwe socket aangemaakt worden waarmee deze
        // met elkaar communiceren
        connectionSocket = welcomeSocket.accept();
        // buffer voor data communicatie tussen server en client
        outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
      } catch (IOException ex) {
        System.out.println("IOException1");
      } // if an I/O error occurs when opening the socket.

      if (outToClient
          != null) // wanneer buffer correct is aangemaakt zal deze niet een null waarde hebben
      {
        // gemaakte variabele doorgeven aan thread
        Connection c = new Connection(connectionSocket, outToClient, fileToSend);
        // thread starten
        c.start();
      }
    }
  }
Esempio n. 7
0
  /** Create the serversocket and use its stream to receive serialized objects */
  public static void main(String args[]) {

    ServerSocket ser = null;
    Socket soc = null;
    String str = null;
    Date d = null;

    try {
      ser = new ServerSocket(8020);
      /*
       * This will wait for a connection to be made to this socket.
       */
      soc = ser.accept();
      InputStream o = soc.getInputStream();
      ObjectInput s = new ObjectInputStream(o);
      str = (String) s.readObject();
      d = (Date) s.readObject();
      s.close();

      // print out what we just received
      System.out.println(str);
      System.out.println(d);
    } catch (Exception e) {
      System.out.println(e.getMessage());
      System.out.println("Error during serialization");
      System.exit(1);
    }
  }
Esempio n. 8
0
  /**
   * serviceClient accepts a client connection and reads lines from the socket. Each line is handed
   * to executeCommand for parsing and execution.
   */
  public void serviceClient() throws java.io.IOException {
    System.out.println("Accepting clients now");
    Socket clientConnection = serverSocket.accept();

    // Arrange to read input from the Socket
    InputStream inputStream = clientConnection.getInputStream();
    bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

    // Arrange to write result across Socket back to client
    OutputStream outputStream = clientConnection.getOutputStream();
    PrintStream printStream = new PrintStream(outputStream);

    System.out.println(
        "Client acquired on port #" + serverSocket.getLocalPort() + ", reading from socket");

    try {
      String commandLine;
      while ((commandLine = bufferedReader.readLine()) != null) {
        try {
          Float result = executeCommand(commandLine);
          // Only BALANCE command returns non-null
          if (result != null) {
            printStream.println(result); // Write it back to the client
          }
        } catch (ATMException atmex) {
          System.out.println("ERROR: " + atmex);
        }
      }
    } catch (SocketException sException) {
      // client has stopped sending commands.  Exit gracefully.
      System.out.println("done");
    }
  }
Esempio n. 9
0
  public static void main(String[] args) throws IOException {
    int servPort = Integer.parseInt(args[0]);
    ServerSocket servSock = new ServerSocket(8080); // cria o socket servidor

    int recvMsgSize; // tamanho da msg
    byte[] byteBuffer = new byte[BufSize]; // buffer de recebimento

    for (; ; ) {
      // espera as solicitações dos clientes
      Socket clntSock = servSock.accept(); // server aceita a conexão
      // imprimi o ip e a porta do servidor
      System.out.println(
          "Controlando o cliente"
              + clntSock.getInetAddress().getHostAddress()
              + "na porta"
              + clntSock.getPort());

      InputStream in = clntSock.getInputStream();
      OutputStream out = clntSock.getOutputStream();

      while ((recvMsgSize = in.read(byteBuffer))
          != -1) // lê a msg a ser transmitida até estourar o tamanho
      out.write(byteBuffer, 0, recvMsgSize);
      clntSock.close(); // fecha o socket do cliente
    }
  }
  @Override
  public void run() {
    try {
      socket = server.accept();
      System.out.println("Download : " + socket.getRemoteSocketAddress());

      In = socket.getInputStream();
      Out = new FileOutputStream(saveTo);

      byte[] buffer = new byte[1024];
      int count;

      while ((count = In.read(buffer)) >= 0) {
        Out.write(buffer, 0, count);
      }

      Out.flush();

      if (Out != null) {
        Out.close();
      }
      if (In != null) {
        In.close();
      }
      if (socket != null) {
        socket.close();
      }
    } catch (Exception ex) {
      System.out.println("Exception [Download : run(...)]");
    }
  }
Esempio n. 11
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. 12
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. 13
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();
    }
  }
Esempio n. 14
0
  public void listen() {

    while (true) {
      Socket clientSoc = null;

      try {
        clientSoc = serverSocket.accept();
      } catch (IOException e) {
        System.out.println("Accept Socket Error");
        System.exit(1);
      }

      /* Send Welcome Message */
      try {
        out = new PrintWriter(clientSoc.getOutputStream(), true);
        out.println("Thank you for connecting");
        System.out.println("Connection successful with client " + clientSoc.getLocalAddress());
        System.out.println("Waiting for input from " + clientSoc.getLocalAddress());
      } catch (IOException e) {
        e.printStackTrace();
      }

      new Thread(new ClientConnected(clientSoc, out)).start();
    }
  }
  private ServerSocketDemo() {
    try {
      ss = new ServerSocket(2002);
      s = ss.accept();

      System.out.println("Server started");
      local = new BufferedReader(new InputStreamReader(System.in));
      remote = new BufferedReader(new InputStreamReader(s.getInputStream()));
      ps = new PrintStream(s.getOutputStream());

      while (true) {
        System.out.println("Type a message to send to the client");
        String localdata = local.readLine();
        ps.println(localdata); // sends the data to output stream
        String remotedata = remote.readLine();
        System.out.println("Client:= " + remotedata);
        if (remotedata.equals("bye")) {
          System.out.println("Client Disconnected");
          break;
        }
      }
    } catch (Exception e) {
      System.out.println("Error in Server" + e);
    }
  }
 /** @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;
     }
   }
 }
Esempio n. 17
0
  public void go() {

    try {
      ServerSocket serverSock = new ServerSocket(4242);

      System.out.println(getTime() + "서버가 준비되었습니다.");
      // ServerSocket을 통해 이 서버 애플리케이션은 이 코드가 실행되고 있는 시스템의 4242번 포트로 들어오는 클라이언트 요청을 감시한다.

      while (true) {
        System.out.println(getTime() + "연결요청을 기다립니다.");
        Socket sock = serverSock.accept();
        sock.setSoTimeout(2000);
        // accept()메소드는 요청이 들어 올때까지 그냥 기다린다. 그리고 클라이언트 요청이 들어오면 클라이언트와 통신을 위해 (현재 쓰이고 있찌 않은 포트에 대한)
        // Socket을 리턴함.
        System.out.println(getTime() + sock.getInetAddress() + "로부터 연결요청이 들어왔습니다.");

        PrintWriter writer = new PrintWriter(sock.getOutputStream());
        String advice = getAdvice();
        writer.println(advice);
        writer.close();
        // 이제 클라이언트에 대한 Socket연결을 써서 PrintWriter를 만들고 클라이언트에 String 조언메시지를 보냄(println() 메소드 사용)
        // 그리고 나면 클라이언트와의 작업이 끝난 것이므로 Socket을 닫는다.

        System.out.println(advice);
      }

    } catch (IOException ex) {
      System.out.println("ssss");
      ex.printStackTrace();
    }
  } // go 메소드
  // 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();
    }
  }
  private void server() {
    new CountDown(60).start();
    while (true) {
      try {
        Socket socket = serverSock.accept();
        System.out.println("New Client:" + socket);
        if (readyState[6] == 1) {
          System.out.println("正在游戏中,无法加入");
          continue;
        }
        for (i = 0; i <= 5; i++) {
          if (players[i].equals("虚位以待")) break;
        }
        if (i > 5) {
          System.out.println("房间已满,无法加入");
          continue;
        }
        i++;
        ObjectOutputStream remoteOut = new ObjectOutputStream(socket.getOutputStream());
        clients.addElement(remoteOut);

        ObjectInputStream remoteIn = new ObjectInputStream(socket.getInputStream());
        new ServerHelder(remoteIn, remoteOut, socket.getPort(), i).start();
      } catch (IOException e) {
        System.out.println(e.getMessage() + ": Failed to connect to client.");
        try {
          serverSock.close();
        } catch (IOException x) {
          System.out.println(e.getMessage() + ": Failed to close server socket.");
        }
      }
    }
  }
Esempio n. 20
0
 /** List file names */
 public Enumeration nlst(String s) throws IOException {
   InetAddress inetAddress = InetAddress.getLocalHost();
   byte ab[] = inetAddress.getAddress();
   serverSocket_ = new ServerSocket(0, 1);
   StringBuffer sb = new StringBuffer(32);
   sb.append("PORT ");
   for (int i = 0; i < ab.length; i++) {
     sb.append(String.valueOf(ab[i] & 255));
     sb.append(",");
   }
   sb.append(String.valueOf(serverSocket_.getLocalPort() >>> 8 & 255));
   sb.append(",");
   sb.append(String.valueOf(serverSocket_.getLocalPort() & 255));
   if (issueCommand(sb.toString()) != FTP_SUCCESS) {
     serverSocket_.close();
     throw new IOException(getResponseString());
   } else if (issueCommand("NLST " + ((s == null) ? "" : s)) != FTP_SUCCESS) {
     serverSocket_.close();
     throw new IOException(getResponseString());
   }
   dataSocket_ = serverSocket_.accept();
   serverSocket_.close();
   serverSocket_ = null;
   Vector v = readServerResponse_(dataSocket_.getInputStream());
   dataSocket_.close();
   dataSocket_ = null;
   return (v == null) ? null : v.elements();
 }
Esempio n. 21
0
  public Server() {
    try {
      ServerSocket ss = new ServerSocket(SERVER_PORT);

      Socket s = ss.accept();

      InputStream is = s.getInputStream();
      OutputStream out = s.getOutputStream();
      InputStreamReader isr = new InputStreamReader(is);
      BufferedReader br = new BufferedReader(isr);

      String sss = br.readLine();
      System.out.println(sss);

      PrintWriter pw = new PrintWriter(out);
      pw.print("hello,我是服务器。");

      pw.close();
      br.close();
      isr.close();
      out.close();
      is.close();
      s.close();
      ss.close();
    } catch (UnknownHostException ue) {
      ue.printStackTrace();
    } catch (IOException oe) {
      oe.printStackTrace();
    }
  }
  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 static void main(String[] args) {

    try {
      System.out.println("Creando socket servidor");

      ServerSocket serverSocket = new ServerSocket();

      System.out.println("Realizando el enlace");
      InetSocketAddress addr = new InetSocketAddress("localhost", 5555);
      serverSocket.bind(addr);

      System.out.println("Aceptando conexiones");
      Socket newSocket = serverSocket.accept();
      System.out.println("Conexión recibida");

      InputStream is = newSocket.getInputStream();
      OutputStream os = newSocket.getOutputStream();

      byte[] mensaje = new byte[25];
      is.read(mensaje);

      System.out.println("Mensaje recibido: " + new String(mensaje));
      System.out.println("Cerrando el nuevo socket");

      newSocket.close();

      System.out.println("Cerrando el socket servidor");
      serverSocket.close();

      System.out.println("Terminado");

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  @SuppressWarnings("resource")
  @Override
  public void run() {
    // TODO Auto-generated method stub
    int i = 0;

    try {

      ServerSocket listener = new ServerSocket(port);
      Socket server;

      while ((i++ < maxConnections) || (maxConnections == 0)) {

        gameController.Print("Server: Waiting for Clients");
        server = listener.accept();
        gameController.Print("Server: Client " + NextClientId() + " Connected.");

        clientFramework.add(new ClientHandler(this, server, NextClientId()));
      }

    } catch (IOException ioe) {
      System.out.println("IOException on socket listen: " + ioe);
      ioe.printStackTrace();
    }
  }
Esempio n. 25
0
  public static void main(String args[]) throws IOException {
    ServerSocket sSocket = new ServerSocket(sPort, 10);

    // Arguments Handling
    if (args.length != 1) {
      System.out.println("Must specify a file-path argument.");
    } else {
      String currentDir = System.getProperty("user.dir");
      filePath = currentDir + "/src/srcFile/" + args[0];
      filename = args[0];
    }

    // Get list of chunks owned
    chunkOwned();

    // Call FileSplitter
    FileSplitter fs = new FileSplitter();
    fs.split(filePath);

    System.out.println("Waiting for connection");
    while (true) {
      Socket connection = sSocket.accept();
      System.out.println("Connection received from " + connection.getInetAddress().getHostName());

      new Thread(new MultiThreadServer(connection)).start();
    }
  }
Esempio n. 26
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();
    }
  }
 /**
  * creates a server socket listening on port specified in the object constructor, and then
  * enters an infinite loop waiting for incoming socket connection requests representing a worker
  * process attempting to connect to this server, which it handles via the enclosing server's
  * <CODE>addNewWorkerConnection(s)</CODE> method.
  */
 public void run() {
   try {
     ServerSocket ss = new ServerSocket(_port);
     System.out.println("Srv: Now Accepting Worker Connections");
     while (true) {
       try {
         Socket s = ss.accept();
         System.out.println("Srv: Incoming New Worker Connection to the Network");
         System.out.println(
             "Srv: Thread may have to wait if an init_cmd has not yet arrived from the client");
         addNewWorkerConnection(s);
         System.out.println("Srv: finished adding new worker connection to the _workers");
       } catch (Exception e) {
         utils.Messenger.getInstance()
             .msg(
                 "PDBTExecSingleCltWrkInitSrv.W2Thread.run(): "
                     + "An error occured while adding new worker connection",
                 2);
         // e.printStackTrace();
       }
     }
   } catch (IOException e) {
     // e.printStackTrace();
     utils.Messenger.getInstance()
         .msg(
             "PDBTExecSingleCltWrkInitSrv.W2Thread.run(): "
                 + "Failed to create Server Socket, Server exiting.",
             0);
     System.exit(-1);
   }
 }
Esempio n. 28
0
  public static void main(String[] args) {
    ServerSocket welcomeSocket; // TCP-Server-Socketklasse
    Socket connectionSocket; // TCP-Standard-Socketklasse

    int counter = 0; // Z�hlt die erzeugten Bearbeitungs-Threads

    try {
      /* Server-Socket erzeugen */
      welcomeSocket = new ServerSocket(SERVER_PORT);

      while (true) { // Server laufen IMMER
        System.out.println(
            "TCP Server: Waiting for connection - listening TCP port " + SERVER_PORT);
        /*
         * Blockiert auf Verbindungsanfrage warten --> nach
         * Verbindungsaufbau Standard-Socket erzeugen und
         * connectionSocket zuweisen
         */
        connectionSocket = welcomeSocket.accept();

        /* Neuen Arbeits-Thread erzeugen und den Socket �bergeben */
        (new TCPServerThread(++counter, connectionSocket)).start();
      }
    } catch (IOException e) {
      System.err.println(e.toString());
    }
  }
Esempio n. 29
0
  public static void main(String[] args) throws IOException {
    ServerSocket serverSocket = null;

    try {
      serverSocket = new ServerSocket(10008);
      System.out.println("Enroll: 130050131071");
      System.out.println("Connection Socket Created");
      try {
        while (true) {
          System.out.println("Waiting for Connection");
          new EchoServer2(serverSocket.accept());
        }
      } catch (IOException e) {
        System.err.println("Accept failed.");
        System.exit(1);
      }
    } catch (IOException e) {
      System.err.println("Could not listen on port: 10008.");
      System.exit(1);
    } finally {
      try {
        serverSocket.close();
      } catch (IOException e) {
        System.err.println("Could not close port: 10008.");
        System.exit(1);
      }
    }
  }
Esempio n. 30
0
  public void run() {
    while (true) {
      try {
        System.out.println("Server name: " + serverSocket.getInetAddress().getHostName());
        System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
        Socket server = serverSocket.accept();
        System.out.println("Just connected to " + server.getRemoteSocketAddress());

        ObjectInputStream objectIn = new ObjectInputStream(server.getInputStream());

        try {
          Recipe rec = (Recipe) objectIn.readObject();
          startHMI(rec, rec.getProductName());

          //				System.out.println("Object Received: width: "+rec.getWidth()+" height:
          // "+rec.getHeight());
        } catch (ClassNotFoundException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }

        DataOutputStream out = new DataOutputStream(server.getOutputStream());
        out.writeUTF(
            "Thank you for connecting to " + server.getLocalSocketAddress() + "\nGoodbye!");
        server.close();
      } catch (SocketTimeoutException s) {
        System.out.println("Socket timed out!");
        break;
      } catch (IOException e) {
        e.printStackTrace();
        break;
      }
    }
  }