コード例 #1
0
ファイル: TimeServer1.java プロジェクト: YDJX/space
  public static void main(String[] args) {
    int port = 8080;
    if (args != null && args.length > 0) {
      try {
        port = Integer.parseInt(args[0], 10);
      } catch (NumberFormatException e) {
        e.printStackTrace();
      }
    }

    ServerSocket servSocket = null;
    try {
      servSocket = new ServerSocket(port);
      System.out.println("The server start in port:" + port);

      Socket socket = null;
      TimeServerHandlerExecutePool singleExecutor = new TimeServerHandlerExecutePool(100, 10000);
      while (true) {
        socket = servSocket.accept();
        singleExecutor.execute(new TimeServerHandler(socket));
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (servSocket != null) {
        try {
          System.out.println("The time server close.");
          servSocket.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
コード例 #2
0
ファイル: Ce102ImplTest.java プロジェクト: psih747/samples
 @Override
 public void run() {
   try {
     ServerSocket ss = new ServerSocket(port);
     while (!interrupted()) {
       try (Socket s = ss.accept(); ) {
         InputStream in = s.getInputStream();
         OutputStream out = s.getOutputStream();
         ChannelLevelInputStream cin = new ChannelLevelInputStream(in);
         ChannelLevelPacket clp = cin.readPacket();
         PALInputStream pin = new PALInputStream(new ByteArrayInputStream(clp.getPacketData()));
         PALRequest req = pin.readRequest();
         PALResponse resp = process(req);
         ByteArrayOutputStream bout = new ByteArrayOutputStream();
         PALOutputStream pout = new PALOutputStream(bout);
         pout.writePALResponse(resp);
         ChannelLevelPacket packet =
             new ChannelLevelPacket(
                 clp.getAddressS(), clp.getAddressD(), 0x48, bout.toByteArray());
         ChannelLevelOutputStream cout = new ChannelLevelOutputStream(out);
         cout.writePacket(packet);
         cout.close();
         cin.close();
         pout.close();
         pin.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
     ss.close();
   } catch (IOException e1) {
     e1.printStackTrace();
     return;
   }
 }
コード例 #3
0
 /**
  * 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
ファイル: EchoServer.java プロジェクト: Kiriian/Sockets-1
 public static void main(String[] args) throws IOException {
   String ip = "localhost";
   int port = 4321;
   if (args.length == 2) {
     ip = args[0];
     port = Integer.parseInt(args[1]);
   }
   ServerSocket ss = new ServerSocket();
   ss.bind(new InetSocketAddress(ip, port));
   Socket s;
   while (true) {
     s = ss.accept();
     BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
     PrintWriter out = new PrintWriter(s.getOutputStream(), true);
     // waits for data and reads it in until connection dies
     // readLine() blocks until the server receives a new line from client
     String str;
     while ((str = in.readLine()) != null) {
       if (str.equals("!!")) {
         System.exit(0);
       }
       out.println(str);
     }
   }
 }
コード例 #5
0
ファイル: Main.java プロジェクト: DaciCop/dacicop
 public static void startServer(int port) {
   ServerSocket ssock;
   // Socket sock;
   // DezactiveazaBonus bonus= new DezactiveazaBonus();
   // Thread b=new Thread(bonus);
   // b.start();
   try {
     ssock = new ServerSocket(port);
     while (true) {
       Socket esock = null;
       try {
         esock = ssock.accept();
         while (listEmpty()) yield();
         // System.out.println("A intrat in bucla");
         assignThread(esock);
       } catch (Exception e) {
         try {
           esock.close();
         } catch (Exception ec) {
         }
       }
       // System.out.println("A iesit din bucla");
     }
   } catch (IOException e) {
   }
 }
コード例 #6
0
  /** 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);
      }
    }
  }
コード例 #7
0
ファイル: Server.java プロジェクト: Kairus101/soccerRobots
  Server() throws IOException {
    if (useSerial) {
      ServerThread.initSerial();
      ServerThread.writeSerial(true);
      try {
        Thread.sleep(200);
      } catch (InterruptedException e1) {
      }
      ServerThread.writeSerial(true);
      try {
        Thread.sleep(200);
      } catch (InterruptedException e1) {
      }
      ServerThread.writeSerial(true);
    }

    int port = 10055;
    ServerSocket serverSocket = null;
    try {
      serverSocket = new ServerSocket(port);
      System.out.println("Soccer robots server active on port " + port + ".");
    } catch (IOException e) {
      System.err.println("Could not listen on port: " + port + ".");
      System.exit(-1);
    }
    while (true) {
      ServerThread tmp = new ServerThread(serverSocket.accept());
      threads.add(tmp);
    }
  }
コード例 #8
0
  public void server() {
    try {
      ss = new ServerSocket(5000);
      socket = ss.accept();
      System.out.println(socket);
      in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      out = new PrintWriter(socket.getOutputStream(), true);
      while (socket.isConnected()) {

        String line = in.readLine();
        System.out.println(line);
        out.println("you input is :" + line);
      }
      out.close();
      in.close();
      socket.close();
    } catch (IOException e) {

    } finally {
      try {
        ss.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
コード例 #9
0
    /** used for start of the thread */
    public void run() {
      ServerSocket sServer = null;
      try {
        /* initialize the server socket*/
        sServer = new ServerSocket(port);
        while (true) {
          /* wait for service */
          Socket socket = sServer.accept();

          /* fill in the receive queue*/
          fillInReceiveQueue(socket);
        }

      } catch (IOException e) {
        e.printStackTrace();
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        try {
          /* close the service */
          sServer.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
コード例 #10
0
ファイル: Main.java プロジェクト: nikolaydymura/socket-server
  public static void main(String[] args) throws Exception {
    ServerSocket server = new ServerSocket(4040);
    while (true) {
      Socket clientSocket = server.accept();
      InputStream is = clientSocket.getInputStream();
      OutputStream os = clientSocket.getOutputStream();

      BufferedReader reader = new BufferedReader(new InputStreamReader(is));

      PrintStream writer = new PrintStream(os, true);

      while (true) {
        String input = reader.readLine();

        System.out.println("input " + input);

        if ("exit".equals(input)) {
          break;
        }

        System.out.println("send " + input);

        writer.println(input);
      }
    }
  }
コード例 #11
0
  private static boolean available(int port) {
    if (port <= 0) {
      throw new IllegalArgumentException("Invalid start port: " + port);
    }

    ServerSocket ss = null;
    DatagramSocket ds = null;
    try {
      ss = new ServerSocket(port);
      ss.setReuseAddress(true);
      ds = new DatagramSocket(port);
      ds.setReuseAddress(true);
      return true;
    } catch (IOException e) {
      LogKit.logNothing(e);
    } finally {
      if (ds != null) {
        ds.close();
      }

      if (ss != null) {
        try {
          ss.close();
        } catch (IOException e) {
          // should not be thrown, just detect port available.
          LogKit.logNothing(e);
        }
      }
    }
    return false;
  }
コード例 #12
0
ファイル: StringUtilsTest.java プロジェクト: Kloudtek/ktutils
 public String decodeUrl(final String path) throws Exception {
   ServerSocket serverSocket = new ServerSocket(0);
   final int port = serverSocket.getLocalPort();
   serverSocket.close();
   Server server = new Server(port);
   server.setStopAtShutdown(true);
   ServletContextHandler ctx = new ServletContextHandler(server, "/", true, false);
   ctx.addServlet(new ServletHolder(new DecodeServlet()), "/*");
   server.start();
   ThreadUtils.sleep(500);
   new Thread() {
     @Override
     public void run() {
       try {
         ThreadUtils.sleep(500);
         InputStream is = new URL("http://localhost:" + port + path).openStream();
       } catch (IOException e) {
         throw new RuntimeException(e);
       }
     }
   }.start();
   synchronized (this) {
     wait();
   }
   return this.decodedPath;
 }
コード例 #13
0
ファイル: TCPServer.java プロジェクト: systemY/TCPFileServer
  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();
      }
    }
  }
コード例 #14
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();
    }
  }
コード例 #15
0
  public void listenSocket() {
    try {
      server = new ServerSocket(4321, 1, new InetSocketAddress(0).getAddress());
      System.out.println(
          "Server is listening on " + server.getInetAddress().getHostName() + ":" + 4321);
    } catch (IOException e) {
      System.out.println("Could not listen on port 4321");
      System.exit(-1);
    }
    try {
      client = server.accept();
      System.out.println("Client connected on port " + 4321);
      has_client = true;
    } catch (IOException e) {
      System.out.println("Accept failed: 4321");
      System.exit(-1);
    }

    try {
      in = new BufferedReader(new InputStreamReader(client.getInputStream()));
      out = new PrintWriter(client.getOutputStream(), true);
    } catch (IOException e) {
      System.out.println("Read failed");
      System.exit(-1);
    }
  }
コード例 #16
0
  /**
   * Checks to see if a specific port is available.
   *
   * @param port the port to check for availability
   * @return <tt>true</tt> if the port is available, <tt>false</tt> otherwise
   */
  public boolean available(int port) {
    if (port < fromPort || port > toPort) {
      throw new IllegalArgumentException("Port outside port range: " + port);
    }

    ServerSocket ss = null;
    DatagramSocket ds = null;
    try {
      ss = new ServerSocket(port);
      ss.setReuseAddress(true);
      ds = new DatagramSocket(port);
      ds.setReuseAddress(true);
      return true;
    } catch (IOException ignored) {
      /* checkstyle drives me nuts */
    } finally {
      if (ds != null) {
        ds.close();
      }

      if (ss != null) {
        try {
          ss.close();
        } catch (IOException ignored) {
          /* checkstyle drives me nuts */
        }
      }
    }

    return false;
  }
コード例 #17
0
  private LauncherServer() throws IOException {
    this.refCount = new AtomicLong(0);

    ServerSocket server = new ServerSocket();
    try {
      server.setReuseAddress(true);
      server.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));

      this.clients = new ArrayList<>();
      this.threadIds = new AtomicLong();
      this.factory = new NamedThreadFactory(THREAD_NAME_FMT);
      this.pending = new ConcurrentHashMap<>();
      this.timeoutTimer = new Timer("LauncherServer-TimeoutTimer", true);
      this.server = server;
      this.running = true;

      this.serverThread =
          factory.newThread(
              new Runnable() {
                @Override
                public void run() {
                  acceptConnections();
                }
              });
      serverThread.start();
    } catch (IOException ioe) {
      close();
      throw ioe;
    } catch (Exception e) {
      close();
      throw new IOException(e);
    }
  }
コード例 #18
0
  public static void main(String[] args) throws IOException {

    // port number hard-coded if it's not given
    int portNumber = 6999;

    // command line input
    if (args.length > 0) {
      portNumber = Integer.parseInt(args[0]);
      if (args.length > 1) num_Students = Integer.parseInt(args[0]);
      if (args.length > 2) TableCapacity = Integer.parseInt(args[1]);
    }

    Event event = new Event(num_Students, TableCapacity);
    boolean listen = true;

    try (ServerSocket serverSocket = new ServerSocket(portNumber)) {

      System.out.println("The server is now running");
      while (listen) {
        new ServerThread(serverSocket.accept(), event).start();
      }
    } catch (IOException e) {
      System.err.println("Could not listen on port " + portNumber);
      System.exit(-1);
    }
  }
コード例 #19
0
ファイル: Server.java プロジェクト: tyom70/ServerSocket
  public static void main(String[] args) {
    try {
      ServerSocket socket = new ServerSocket(8606, 50, InetAddress.getByName("localhost"));
      Socket client = socket.accept();

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

      DataOutputStream dout = new DataOutputStream(out);
      DataInputStream din = new DataInputStream(in);

      String line = null;

      while (true) {
        line = din.readUTF();
        System.out.println(line);
        dout.writeUTF(line);
      }

    } catch (UnknownHostException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
コード例 #20
0
    public void run() {

      try {
        isStarting = true;
        synchronized (this) {
          serverSocket = new ServerSocket(0);
          this.port = serverSocket.getLocalPort();
          setRunning(true);
          isStarting = false;
          this.notifyAll();
        }

        System.err.println("Child-process heartbeat server started on port: " + port);

        while (true) {
          Socket sock = serverSocket.accept();
          log("Got heartbeat connection from client; starting heartbeat.");
          synchronized (heartBeatThreads) {
            HeartbeatThread hbt = new HeartbeatThread(sock);
            heartBeatThreads.add(hbt);
            hbt.start();
          }
        }
      } catch (Exception e) {
        if (!running) log("Heartbeat server was shutdown.");
        else log("Got expcetion in heartbeat server: " + e.getMessage());
      } finally {
        setRunning(false);
        log("Heartbeat server terminated.");
      }
    }
コード例 #21
0
ファイル: Server.java プロジェクト: piyushagade/BitSync
  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();
    }
  }
コード例 #22
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");
  }
コード例 #23
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);
    }
  }
コード例 #24
0
ファイル: Server.java プロジェクト: wangyif2/EncProvider
  public static void main(String[] args) throws IOException, ClassNotFoundException {
    ServerSocket serverSocket = null;
    boolean listening = true;
    Class.forName("org.sqlite.JDBC");

    try {
      if (args.length == 1) {
        serverSocket = new ServerSocket(Integer.parseInt(args[0]));
        System.out.println(
            "Server up and running with:\nhostname: " + getLocalIpAddress() + "\nport: " + args[0]);
        System.out.println("Waiting to accept client...");
        System.out.println("Remember to setup client hostname");
      } else {
        System.err.println("ERROR: Invalid arguments!");
        System.exit(-1);
      }
    } catch (IOException e) {
      System.err.println("ERROR: Could not listen on port!");
      System.exit(-1);
    }

    while (listening) {
      new ServerHandlerThread(serverSocket.accept()).start();
    }

    serverSocket.close();
  }
コード例 #25
0
  public void run() {
    ServerSocket server = null;
    try {
      server = new ServerSocket(link.getSerPort());
      System.out.println("System Online!");
    } catch (Exception e) {
      e.printStackTrace();
      return;
    }
    try {
      Socket remoteSocket = server.accept();
      System.out.println("remoteSocket accpet!");
      Socket localSocket = server.accept();
      System.out.println("localSocket  accpet!");
      remoteSocket.setSoTimeout(0);
      localSocket.setSoTimeout(0);

      remoteSocket.setTcpNoDelay(true);
      localSocket.setTcpNoDelay(true);

      new TransferDown(remoteSocket, localSocket, "ToCZ");
      new TransferUp(remoteSocket, localSocket, "ToYonYou");

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #26
0
  @Override
  public void run() {
    try {
      if (socket != null && !socket.isClosed()) {
        while (true) {
          Log.i("Server Started", "Server Started");
          fileSocket = socket.accept();
          Log.i("RF Sever Accepted", "accepted saving now");
          saveFile(fileSocket);

          new Thread(new SendEndMsg(Home.current)).start(); /*to send free me msg*/
        }
      } else Log.i("Error", "file Port Already Bind Close Reconnect");
    } catch (IOException e) {
      Log.i("RFSever Accepted", "IO");
      e.printStackTrace();
    } catch (Exception e) {
      Log.i("RFSever Accepted", "EX");
      e.printStackTrace();
    }
    {
      Log.i("RF FAIL", "Is closed check");
      if (socket != null && !socket.isClosed()) {
        try {
          Log.i("FAIL", "Closing");
          socket.close();
        } catch (IOException e) {

          Log.i("FAIL", "Fail to close socket");
          e.printStackTrace();
        }
      }
    }
  }
コード例 #27
0
 /**
  * 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 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();
    }
  }
コード例 #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);
      }
    }
  }
コード例 #30
0
  /**
   * Test of a large write on a socket to understand what happens when the write is greater than the
   * combined size of the client send buffer and the server receive buffer and the server side of
   * the socket is either not accepted or already shutdown.
   *
   * @throws IOException
   * @throws InterruptedException
   */
  public void testDirectSockets_largeWrite_NotAccepted() throws IOException, InterruptedException {

    final Random r = new Random();

    // Get a socket addresss for an unused port.
    final InetSocketAddress serverAddr = new InetSocketAddress(getPort(0));

    // First our ServerSocket
    final ServerSocket ss = new ServerSocket();
    try {

      // Size of the server socket receive buffer.
      final int receiveBufferSize = ss.getReceiveBufferSize();

      // Allocate buffer twice as large as the receive buffer.
      final byte[] largeBuffer = new byte[receiveBufferSize * 10];

      if (log.isInfoEnabled()) {
        log.info(
            "receiveBufferSize=" + receiveBufferSize + ", largeBufferSize=" + largeBuffer.length);
      }

      // fill buffer with random data.
      r.nextBytes(largeBuffer);

      // bind the ServerSocket to the specified port.
      ss.bind(serverAddr);

      // Now the first Client SocketChannel
      final SocketChannel cs = SocketChannel.open();
      try {
        /*
         * Note: true if connection made. false if connection in
         * progress.
         */
        final boolean immediate = cs.connect(serverAddr);
        if (!immediate) {
          // Did not connect immediately, so finish connect now.
          if (!cs.finishConnect()) {
            fail("Did not connect.");
          }
        }

        /*
         * Attempt to write data. The server socket is not yet accepted.
         * This should hit a timeout.
         */
        assertTimeout(10L, TimeUnit.SECONDS, new WriteBufferTask(cs, ByteBuffer.wrap(largeBuffer)));

        accept(ss);

      } finally {
        cs.close();
      }

    } finally {

      ss.close();
    }
  }