예제 #1
0
파일: Server.java 프로젝트: ThierryL/PacMan
  private static void serverWaiting() throws Exception {
    System.out.println("Waiting Mode");
    ServerSocket waitingSocket = new ServerSocket(serverInfo.getPort());
    String line;

    while (true) {
      Socket connectionSocket = waitingSocket.accept();
      BufferedReader in =
          new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
      DataOutputStream out = new DataOutputStream(connectionSocket.getOutputStream());
      // System.out.println("Waiting for migration");
      line = in.readLine();
      // System.out.println("Received: " + line);
      String info = line;
      out.writeBytes("Info OK\n");
      line = in.readLine();
      // System.out.println("Received: " + line);
      serverInit();
      game.setMoving(true);
      reconstruction(info);
      out.writeBytes("Bind OK\n");
      waitingSocket.close();
      break;
    }
    while (!allConnected) {
      System.out.print("");
    }
    game.setMoving(false);
    // System.out.println("Fin server waiting");
    serverRunning();
  }
예제 #2
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 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);
   }
 }
예제 #4
0
  public TCPConnectionMap(
      String service_name,
      ThreadFactory f,
      SocketFactory socket_factory,
      Receiver r,
      InetAddress bind_addr,
      InetAddress external_addr,
      int srv_port,
      int max_port,
      long reaper_interval,
      long conn_expire_time)
      throws Exception {
    this.mapper = new Mapper(f, reaper_interval);
    this.receiver = r;
    this.bind_addr = bind_addr;
    this.conn_expire_time = conn_expire_time;
    if (socket_factory != null) this.socket_factory = socket_factory;
    this.srv_sock =
        Util.createServerSocket(this.socket_factory, service_name, bind_addr, srv_port, max_port);

    if (external_addr != null) local_addr = new IpAddress(external_addr, srv_sock.getLocalPort());
    else if (bind_addr != null) local_addr = new IpAddress(bind_addr, srv_sock.getLocalPort());
    else local_addr = new IpAddress(srv_sock.getLocalPort());

    acceptor = f.newThread(thread_group, new ConnectionAcceptor(), "ConnectionMap.Acceptor");
  }
  /** 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);
      }
    }
  }
  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.");
        }
      }
    }
  }
예제 #7
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();
    }
  }
예제 #8
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");
    }
  }
예제 #9
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();
    }
  }
예제 #10
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) {
     }
   }
 }
예제 #11
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();
    }
  }
예제 #12
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;
      }
    }
  }
예제 #13
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();
   }
 }
예제 #14
0
 public static void main(String[] args) {
   try {
     ServerSocket server = null;
     try {
       server = new ServerSocket(4700);
     } catch (Exception e) {
       System.out.println("Can Not Listem To:" + e);
     }
     Socket socket = null;
     try {
       socket = server.accept();
     } catch (Exception e) {
       System.out.println("Error: " + e);
     }
     String line;
     BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
     PrintWriter os = new PrintWriter(socket.getOutputStream());
     BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
     System.out.println("Client:" + is.readLine());
     line = sin.readLine();
     while (!line.equals("bye")) {
       os.println(line);
       os.flush();
       System.out.println("Server:" + line);
       System.out.println("Client:" + is.readLine());
       line = sin.readLine();
     }
     os.close();
     is.close();
     socket.close();
     server.close();
   } catch (Exception e) {
     System.out.println("Error:" + e);
   }
 }
예제 #15
0
 private void writeHostAndPortToFile(File portFile) {
   String host = socket.getInetAddress().getHostName();
   int port = socket.getLocalPort();
   // The motivation for the Log.warn would be better satisfied by Bug 38.
   Log.warn("echo " + host + ":" + port + " > " + portFile);
   StringUtilities.writeFile(portFile, host + ":" + port + "\n");
 }
예제 #16
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
    }
  }
예제 #17
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");
    }
  }
예제 #18
0
  // 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();
    }
  }
예제 #19
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);
    }
  }
  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();
  }
예제 #21
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();
      }
    }
  }
  @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();
    }
  }
  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();
    }
  }
예제 #24
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();
    }
  }
예제 #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();
    }
  }
예제 #26
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());
    }
  }
 /**
  * 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);
   }
 }
예제 #28
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 메소드
예제 #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);
      }
    }
  }
  public static void main(String[] args) throws IOException {
    ServerSocket serverSocket = null;
    boolean listening = true;
    // creating an instance of peernode object
    PeerNode peer = new PeerNode();
    if (args.length > 0) {
      peer.ProcessFileInputArgs(args);
      peer.run();

      try {
        serverSocket = new ServerSocket(Integer.parseInt(peer.getPort()));
        System.out.println("Server " + peer.getID() + " Started!");
      } catch (IOException e) {
        System.err.println("Could not listen on port: " + Integer.parseInt(peer.getPort()));
        System.exit(-1);
      }
      // passing the object to the ServerThread object
      while (listening) new ServerThread(serverSocket.accept(), peer).start();

      serverSocket.close();
    } else {
      System.out.println(
          "This program requires switches in the command line. i.e java peer -i 10 -h ubuntu -p 2113 -m 32 -r ubuntu -s 2112");
    }
  }