示例#1
1
 private synchronized void abort() {
   if (mode == ABORT_MODE) {
     return;
   }
   mode = ABORT_MODE;
   try {
     log.info("Aborting operation");
     if (remote_sock != null) {
       remote_sock.close();
     }
     if (sock != null) {
       sock.close();
     }
     if (relayServer != null) {
       relayServer.stop();
     }
     if (ss != null) {
       ss.close();
     }
     if (pipe_thread1 != null) {
       pipe_thread1.interrupt();
     }
     if (pipe_thread2 != null) {
       pipe_thread2.interrupt();
     }
   } catch (final IOException ioe) {
   }
 }
 public int ReadDb(Socket sock, String path) throws IOException {
   DataInputStream dis =
       new DataInputStream(sock.getInputStream()); // get the socket's input stream
   String c = dis.readUTF();
   if (c.contains("ok")) {
     System.out.println("file esistente sul server");
   } else if (c.contains("notfound")) {
     screenAlert("Periodo di tempo non esistente sul server");
     System.out.println("file non esistente sul server");
     dis.close();
     sock.close();
     return 0;
   }
   InputStream in = sock.getInputStream();
   FileOutputStream out = new FileOutputStream(path);
   byte[] buf = new byte[80192]; // buffer
   int len = 0;
   while ((len = in.read(buf)) != -1) {
     out.write(buf, 0, len); // write buffer
     System.out.println("reading " + len);
   }
   dis.close();
   out.flush();
   out.close();
   in.close();
   sock.close();
   return 1;
 }
 public void run() {
   try {
     BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
     String inString;
     while (sessionIsRunning && (inString = in.readLine()) != null) {
       logger.finer(
           "Received: " + inString + " from " + socket.getRemoteSocketAddress().toString());
       String result = executeCommandLine(inString);
       if (result == null) {
         break;
       }
       result += "\n\r";
       socket.getOutputStream().write(result.getBytes());
       messageCount++;
     }
     socket.close();
   } catch (Exception e) {
     if (sessionIsRunning) {
       logger.warning("Failed reading from socket in TCPCommandPort " + e);
       try {
         socket.close();
       } catch (IOException e1) {
         // OK, close failed - not much to do about it...
       }
     }
   }
   sessionIsRunning = false;
   // We are done closing down actions, remove us from list of active
   // sessions
   sessions.remove(this);
   logger.info("Disconnected from " + remoteAddress);
 }
  /**
   * Target and initiator should successfully connect to a "remote" SOCKS5 proxy and the initiator
   * activates the bytestream.
   *
   * @throws Exception should not happen
   */
  @Test
  public void shouldSuccessfullyEstablishConnectionAndActivateSocks5Proxy() throws Exception {

    // build activation confirmation response
    IQ activationResponse =
        new IQ() {

          @Override
          public String getChildElementXML() {
            return null;
          }
        };
    activationResponse.setFrom(proxyJID);
    activationResponse.setTo(initiatorJID);
    activationResponse.setType(IQ.Type.RESULT);

    protocol.addResponse(
        activationResponse,
        Verification.correspondingSenderReceiver,
        Verification.requestTypeSET,
        new Verification<Bytestream, IQ>() {

          public void verify(Bytestream request, IQ response) {
            // verify that the correct stream should be activated
            assertNotNull(request.getToActivate());
            assertEquals(targetJID, request.getToActivate().getTarget());
          }
        });

    // start a local SOCKS5 proxy
    Socks5TestProxy socks5Proxy = Socks5TestProxy.getProxy(proxyPort);
    socks5Proxy.start();

    StreamHost streamHost = new StreamHost(proxyJID, socks5Proxy.getAddress());
    streamHost.setPort(socks5Proxy.getPort());

    // create digest to get the socket opened by target
    String digest = Socks5Utils.createDigest(sessionID, initiatorJID, targetJID);

    Socks5ClientForInitiator socks5Client =
        new Socks5ClientForInitiator(streamHost, digest, connection, sessionID, targetJID);

    Socket initiatorSocket = socks5Client.getSocket(10000);
    InputStream in = initiatorSocket.getInputStream();

    Socket targetSocket = socks5Proxy.getSocket(digest);
    OutputStream out = targetSocket.getOutputStream();

    // verify test data
    for (int i = 0; i < 10; i++) {
      out.write(i);
      assertEquals(i, in.read());
    }

    protocol.verifyAll();

    initiatorSocket.close();
    targetSocket.close();
    socks5Proxy.stop();
  }
示例#5
0
文件: F.java 项目: ballon/hz
  public static void main(String[] args) throws IOException, InterruptedException {
    for (int iter = 1; iter <= 1000; ++iter) {
      System.out.println("HELLO");

      // ask for a value
      Socket s1 = new Socket("127.0.0.1", 12345);
      PrintWriter out = new PrintWriter(s1.getOutputStream(), true);
      BufferedReader in = new BufferedReader(new InputStreamReader(s1.getInputStream()));
      out.println(-1);
      String response = in.readLine();
      s1.close();
      out.close();
      in.close();

      // increase by 1
      int val = Integer.parseInt(response);
      val++;

      // set value
      Socket s2 = new Socket("127.0.0.1", 12345);
      out = new PrintWriter(s2.getOutputStream(), true);
      in = new BufferedReader(new InputStreamReader(s2.getInputStream()));
      out.println(val);
      s2.close();
      out.close();
      in.close();
    }
  }
 /**
  * login using supplied user/pwd. Note that login must be the first command if used
  *
  * @param user username
  * @param pwd password
  * @return returns <code>true</code> on success
  */
 public void login(String user, String pwd) throws RSrvException {
   if (!authReq) return;
   if (!connected || rt == null) throw new RSrvException(this, "Not connected");
   if (authType == AT_crypt) {
     if (Key == null) Key = "rs";
     Rpacket rp = rt.request(Rtalk.CMD_login, user + "\n" + jcrypt.crypt(Key, pwd));
     if (rp != null && rp.isOk()) return;
     try {
       s.close();
     } catch (Exception e) {
     }
     ;
     is = null;
     os = null;
     s = null;
     connected = false;
     throw new RSrvException(this, "login failed", rp);
   }
   Rpacket rp = rt.request(Rtalk.CMD_login, user + "\n" + pwd);
   if (rp != null && rp.isOk()) return;
   try {
     s.close();
   } catch (Exception e) {
   }
   ;
   is = null;
   os = null;
   s = null;
   connected = false;
   throw new RSrvException(this, "login failed", rp);
 }
示例#7
0
 @Override
 public void run() {
   try {
     BufferedReader in = new BufferedReader(new InputStreamReader(cc.getInputStream()));
     while ((line = in.readLine()) != null) {
       ss = new StringTokenizer(line, ",");
       Point p = new Point();
       p.x = Float.parseFloat(ss.nextToken());
       p.y = Float.parseFloat(ss.nextToken());
       synchronized (points) {
         if (!points.contains(p)) points.add(p);
         postInvalidate();
       }
     }
     cc.close();
   } catch (Exception e) {
     e.printStackTrace();
     try {
       cc.close();
     } catch (IOException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
     }
   }
 }
示例#8
0
  private void sendcursor(float x, float y) {
    // TODO Auto-generated method stub
    Socket sock = null;
    try {

      for (String s : iplist) {
        try {
          InetAddress serverAddr = InetAddress.getByName(s);
          sock = new Socket(serverAddr, 8090);

          PrintWriter out =
              new PrintWriter(
                  new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())), true);
          Log.d("On :  " + ownip, "Sending data to : " + serverAddr);
          out.println(x + "," + y);
          out.flush();

        } catch (IOException i) {
          //	Log.e("serializeObject", "error", i);
        }
        sock.close();
      }

    } catch (Exception e) {
      try {
        sock.close();
      } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }
      Log.e("SA Error", "SERVER: Error in Sending to Client", e);
    }
  }
  public void run() {
    // System.out.println("BBBBBB");
    try {
      // System.out.println("BBBBBB1");
      BufferedReader buff = new BufferedReader(new InputStreamReader(sessionSkt.getInputStream()));
      // System.out.println("BBBBBB2");
      PrintWriter out = new PrintWriter(sessionSkt.getOutputStream());
      // System.out.println("BBBBBB3");
      String msg = null;
      // System.out.println("BBBBBB4");
      while ((msg = buff.readLine()) != null) {
        // System.out.println("BBBBBB5");
        if (msg.equals(VertexCounterProtocol.EXIT)) {
          out.println(VertexCounterProtocol.EXIT_ACK);
          out.flush();
          sessionSkt.close();
          break;
        } else {
          // out.println(msg);
          // out.flush();
          process(msg, buff, out);
        }
        // System.out.println("BBBBBB6");
      }
      // System.out.println("BBBBBB7777777->>exit");

      out.println(VertexCounterProtocol.EXIT_ACK);
      out.flush();
      sessionSkt.close();

    } catch (IOException e) {
      Logger_Java.error("Error : " + e.getMessage());
    }
    // System.out.println("BBBBBB888888->>exit");
  }
示例#10
0
 private void passTcpFileDescriptor(
     LocalSocket fdSocket,
     OutputStream outputStream,
     String socketId,
     String dstIp,
     int dstPort,
     int connectTimeout)
     throws Exception {
   Socket sock = new Socket();
   sock.setTcpNoDelay(true); // force file descriptor being created
   if (protect(sock)) {
     try {
       sock.connect(new InetSocketAddress(dstIp, dstPort), connectTimeout);
       ParcelFileDescriptor fd = ParcelFileDescriptor.fromSocket(sock);
       tcpSockets.put(socketId, sock);
       fdSocket.setFileDescriptorsForSend(new FileDescriptor[] {fd.getFileDescriptor()});
       outputStream.write('*');
       outputStream.flush();
       fd.detachFd();
     } catch (ConnectException e) {
       LogUtils.e("connect " + dstIp + ":" + dstPort + " failed");
       outputStream.write('!');
       sock.close();
     } catch (SocketTimeoutException e) {
       LogUtils.e("connect " + dstIp + ":" + dstPort + " failed");
       outputStream.write('!');
       sock.close();
     } finally {
       outputStream.flush();
     }
   } else {
     LogUtils.e("protect tcp socket failed");
   }
 }
示例#11
0
  public void ListenAndDo() {
    try {
      while (true) {

        in = new ObjectInputStream(new BufferedInputStream(sockt.getInputStream()));

        Packet message = (Packet) in.readObject();
        Log.outString("Packet received from server (opcode :" + message.getOpcode() + ")");

        if (message.getOpcode().equals(0x07)) break;

        TreatPacket(message);
        sleep(100);
      }
      Log.outTimed("Close connection with server");
      sockt.close();
    } catch (SocketTimeoutException ste) {
      Log.outTimed("Server connection timeout");
    } catch (EOFException e) {
      try {
        sockt.close();
      } catch (IOException e1) {
        this.interrupt();
      }
      this.interrupt();
    } catch (SocketException e) {
      this.interrupt();
    } catch (Exception e) {
      e.printStackTrace();
      this.interrupt();
    }
  }
  // make an incoming to the servent, wait a little, and then make sure
  // it asks for a connect back again
  public void testTCPExpireRequestsSent() throws Exception {
    drainAll();
    for (int i = 0; i < 2; i++) {
      Socket s = new Socket("localhost", PORT);
      s.close();
      Thread.sleep(100);
      // Socket must have said CONNECT BACK
      assertFalse(networkManager.acceptedIncomingConnection());

      s = new Socket("localhost", PORT);
      s.getOutputStream().write(StringUtils.toAsciiBytes("CONNECT BACK\r\r"));
      Thread.sleep(500);
      s.close();
      // Socket must have said CONNECT BACK
      assertTrue(networkManager.acceptedIncomingConnection());

      // wait until the expire time is realized
      Thread.sleep(MY_EXPIRE_TIME + MY_VALIDATE_TIME + 1000);

      // it should send off more requests
      assertFalse(networkManager.acceptedIncomingConnection());
      Message m = null;
      do {
        m = testUP[0].receive(TIMEOUT);
      } while (!(m instanceof TCPConnectBackVendorMessage));
    }
  }
示例#13
0
  /**
   * Accept the next incoming connection.
   *
   * <p>When a new peer connects to this service, wait for it to send its handshake. We then parse
   * and check that the handshake advertises the torrent hash we expect, then reply with our own
   * handshake.
   *
   * <p>If everything goes according to plan, notify the <code>IncomingConnectionListener</code>s
   * with the connected socket and the parsed peer ID.
   */
  private void accept() throws IOException, SocketTimeoutException {
    Socket socket = this.socket.accept();

    try {
      logger.debug("New incoming connection ...");
      Handshake hs = this.validateHandshake(socket, null);
      this.sendHandshake(socket);
      this.fireNewPeerConnection(socket, hs.getPeerId());
    } catch (ParseException pe) {
      logger.debug("Invalid handshake from {}: {}", this.socketRepr(socket), pe.getMessage());
      try {
        socket.close();
      } catch (IOException e) {
      }
    } catch (IOException ioe) {
      logger.debug(
          "An error occured while reading an incoming " + "handshake: {}", ioe.getMessage());
      try {
        if (!socket.isClosed()) {
          socket.close();
        }
      } catch (IOException e) {
        // Ignore
      }
    }
  }
示例#14
0
    @Override
    public void run() {
      Socket socket = new Socket();
      InetSocketAddress address = new InetSocketAddress(this.peer.getIp(), this.peer.getPort());

      try {
        logger.info("Connecting to {}...", this.peer);
        socket.connect(address, 3 * 1000);

        this.handler.sendHandshake(socket);
        Handshake hs =
            this.handler.validateHandshake(
                socket, (this.peer.hasPeerId() ? this.peer.getPeerId().array() : null));
        logger.info(
            "Handshaked with {}, peer ID is {}.",
            this.peer,
            Torrent.byteArrayToHexString(hs.getPeerId()));
        this.handler.fireNewPeerConnection(socket, hs.getPeerId());
      } catch (IOException ioe) {
        try {
          socket.close();
        } catch (IOException e) {
        }
        this.handler.fireFailedConnection(this.peer, ioe);
      } catch (ParseException pe) {
        try {
          socket.close();
        } catch (IOException e) {
        }
        this.handler.fireFailedConnection(this.peer, pe);
      }
    }
示例#15
0
  void SocketTests() throws Exception {
    Socket s1 = new Socket();

    test("Socket should be created with SO_REUSEADDR disabled");
    check(!s1.getReuseAddress());

    test("Socket.setReuseAddress(true)");
    s1.setReuseAddress(true);
    check(s1.getReuseAddress());

    test("Socket.setReuseAddress(false)");
    s1.setReuseAddress(false);
    check(!s1.getReuseAddress());

    /* bind to any port */
    s1.bind(new InetSocketAddress(0));

    test("Binding Socket to port already in use should throw " + "a BindException");
    Socket s2 = new Socket();
    try {
      s2.bind(new InetSocketAddress(s1.getLocalPort()));
      failed();
    } catch (BindException e) {
      passed();
    }
    s2.close();

    s1.close();
  }
示例#16
0
 public void createConnection() {
   try {
     Log.v("1111", "1111");
     socket2 = new Socket();
     Log.v("2222", "2222");
     socket2.connect(new InetSocketAddress(ip, port), 15 * 1000);
     Log.v("3333", "3333");
   } catch (UnknownHostException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     if (socket2 != null) {
       try {
         socket2.close();
       } catch (IOException e1) {
         // TODO Auto-generated catch block
         e1.printStackTrace();
       }
     }
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     if (socket2 != null) {
       try {
         socket2.close();
       } catch (IOException e1) {
         // TODO Auto-generated catch block
         e1.printStackTrace();
       }
     }
   } finally {
   }
 }
示例#17
0
  /** Main loop of the SMTP server. */
  public void run() {
    stopped = false;
    try {
      try {
        serverSocket = new ServerSocket(port);
        serverSocket.setSoTimeout(TIMEOUT); // Block for maximum of 1.5
        // seconds
      } finally {
        synchronized (this) {
          // Notify when server socket has been created
          notifyAll();
        }
      }

      // Server: loop until stopped
      while (!isStopped()) {
        // Start server socket and listen for client connections
        Socket socket = null;
        try {
          socket = serverSocket.accept();
        } catch (Exception e) {
          if (socket != null) {
            socket.close();
          }
          continue; // Non-blocking socket timeout occurred: try
          // accept() again
        }

        // Get the input and output streams
        BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintWriter out = new PrintWriter(socket.getOutputStream());

        synchronized (this) {
          /*
           * We synchronize over the handle method and the list update
           * because the client call completes inside the handle
           * method and we have to prevent the client from reading the
           * list until we've updated it. For higher concurrency, we
           * could just change handle to return void and update the
           * list inside the method to limit the duration that we hold
           * the lock.
           */
          List<SmtpMessage> msgs = handleTransaction(out, input);
          receivedMail.addAll(msgs);
        }
        socket.close();
      }
    } catch (Exception e) {
      // TODO Should throw an appropriate exception here.
      e.printStackTrace();
    } finally {
      if (serverSocket != null) {
        try {
          serverSocket.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
示例#18
0
 public void sendToServer(Drawable object) throws DrawErrorException {
   Socket connection = null;
   ObjectOutputStream oos = null;
   ObjectInputStream ois = null;
   try {
     connection = new Socket(ip, 8088);
     oos = new ObjectOutputStream(connection.getOutputStream());
     ois = new ObjectInputStream(connection.getInputStream());
     oos.writeObject(object);
     Object o;
     try {
       while ((o = ois.readObject()) != null) {
         if (o instanceof Throwable) {
           connection.close();
           throw new DrawErrorException((Throwable) o);
         }
       }
     } catch (EOFException e) {
     }
   } catch (IOException | ClassNotFoundException e) {
     throw new DrawErrorException(e);
   } finally {
     try {
       if (connection != null) connection.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
  @Override
  public void run() {
    try {
      BufferedReader in =
          new BufferedReader(
              new InputStreamReader(clientSocket.getInputStream(), Constants.TELNET_ENCODING));
      PrintWriter out =
          new PrintWriter(
              new OutputStreamWriter(clientSocket.getOutputStream(), Constants.TELNET_ENCODING));

      String firstLine;
      while ((firstLine = in.readLine()) != null) {
        String res = kv.process(firstLine);
        out.write(res);
        out.flush();
      }

      clientSocket.close();

    } catch (Exception ex) {
      try {
        clientSocket.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
      ex.printStackTrace();
    }
  }
示例#20
0
 public void receive() throws IOException, InterruptedException {
   Socket socket = null;
   socket = serverSocket.accept();
   BufferedReader br = getReader(socket);
   for (int i = 0; i < 20; i++) {
     String msg = br.readLine();
     System.out.println("receive:" + msg);
     TimeUnit.MILLISECONDS.sleep(1000);
     if (i == 2) {
       if (stopWay == SUDDEN_STOP) {
         System.out.println("突然终止程序");
         System.exit(0);
       }
       if (stopWay == SOCKET_STOP) {
         System.out.println("关闭Socket并终止程序");
         socket.close();
         break;
       }
       if (stopWay == INPUT_STOP) {
         System.out.println("关闭输入流并终止程序");
         socket.shutdownInput();
         break;
       }
       if (stopWay == SERVERSOCKET_STOP) {
         System.out.println("关闭ServerSocket并终止程序");
         serverSocket.close();
         break;
       }
     }
   }
   if (stopWay == NATURAL_STOP) {
     socket.close();
     serverSocket.close();
   }
 }
示例#21
0
  /** Internal method. Connect to searchd and exchange versions. */
  private Socket _Connect() {
    if (_socket != null) return _socket;

    _connerror = false;
    Socket sock = null;
    try {
      sock = new Socket();
      sock.setSoTimeout(_timeout);
      InetSocketAddress addr = new InetSocketAddress(_host, _port);
      sock.connect(addr, _timeout);

      DataInputStream sIn = new DataInputStream(sock.getInputStream());
      int version = sIn.readInt();
      if (version < 1) {
        sock.close();
        _error = "expected searchd protocol version 1+, got version " + version;
        return null;
      }

      DataOutputStream sOut = new DataOutputStream(sock.getOutputStream());
      sOut.writeInt(VER_MAJOR_PROTO);

    } catch (IOException e) {
      _error = "connection to " + _host + ":" + _port + " failed: " + e;
      _connerror = true;

      try {
        if (sock != null) sock.close();
      } catch (IOException e1) {
      }
      return null;
    }

    return sock;
  }
  @Override
  public void run() {
    Socket connection = null;

    while (true) {
      try {
        connection = _serverSocket.accept();
        if (Config.FLOOD_PROTECTION) {
          ForeignConnection fConnection =
              _floodProtection.get(connection.getInetAddress().getHostAddress());
          if (fConnection != null) {
            fConnection.connectionNumber += 1;
            if ((fConnection.connectionNumber > Config.FAST_CONNECTION_LIMIT
                    && (System.currentTimeMillis() - fConnection.lastConnection)
                        < Config.NORMAL_CONNECTION_TIME)
                || (System.currentTimeMillis() - fConnection.lastConnection)
                    < Config.FAST_CONNECTION_TIME
                || fConnection.connectionNumber > Config.MAX_CONNECTION_PER_IP) {
              fConnection.lastConnection = System.currentTimeMillis();
              connection.close();
              fConnection.connectionNumber -= 1;
              if (!fConnection.isFlooding)
                _log.warning(
                    "Potential Flood from " + connection.getInetAddress().getHostAddress());
              fConnection.isFlooding = true;
              continue;
            }
            if (fConnection
                .isFlooding) // if connection was flooding server but now passed the check
            {
              fConnection.isFlooding = false;
              _log.info(
                  connection.getInetAddress().getHostAddress()
                      + " is not considered as flooding anymore.");
            }
            fConnection.lastConnection = System.currentTimeMillis();
          } else {
            fConnection = new ForeignConnection(System.currentTimeMillis());
            _floodProtection.put(connection.getInetAddress().getHostAddress(), fConnection);
          }
        }
        addClient(connection);
      } catch (Exception e) {
        try {
          connection.close();
        } catch (Exception e2) {
        }
        if (this.isInterrupted()) {
          // shutdown?
          try {
            _serverSocket.close();
          } catch (IOException io) {
            _log.log(Level.INFO, "", io);
          }
          break;
        }
      }
    }
  }
  protected void closePeers(Socket socket, ServerSocket serverSocket) throws IOException {

    socket.close();

    socket = serverSocket.accept();

    socket.close();
  }
示例#24
0
 public void closeAll() {
   try {
     slave.close();
     master.close();
   } catch (IOException e) {
     //
   }
 }
示例#25
0
 private void closeSockets() {
   try {
     initiator.close();
     target.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
示例#26
0
  public void run() {
    while (serverSocket != null) {
      Socket socket = null;
      try {
        socket = serverSocket.accept();
        socket.setSoLinger(false, 0);
        LineNumberReader lin = new LineNumberReader(new InputStreamReader(socket.getInputStream()));

        String key = lin.readLine();
        if (!this.key.equals(key)) {
          continue;
        }
        String cmd = lin.readLine();
        if ("stop".equals(cmd)) {
          try {
            socket.close();
          } catch (Exception e) {
            LOGGER.debug("Exception when stopping server", e);
          }
          try {
            socket.close();
          } catch (Exception e) {
            LOGGER.debug("Exception when stopping server", e);
          }
          try {
            serverSocket.close();
          } catch (Exception e) {
            LOGGER.debug("Exception when stopping server", e);
          }

          serverSocket = null;

          try {
            LOGGER.info("Stopping server due to received '{}' command...", cmd);
            server.stop();
          } catch (Exception e) {
            LOGGER.error("Exception when stopping server", e);
          }

          // We've stopped the server. No point hanging around any more...
          return;
        } else {
          LOGGER.info("Unsupported monitor operation");
        }
      } catch (Exception e) {
        LOGGER.error("Exception during monitoring Server", e);
      } finally {
        if (socket != null) {
          try {
            socket.close();
          } catch (Exception e) {
            LOGGER.debug("Exception when stopping server", e);
          }
        }
        socket = null;
      }
    }
  }
示例#27
0
  @Test
  public void testHalfCloseClientServer() throws Exception {
    ServerSocketChannel connector = ServerSocketChannel.open();
    connector.socket().bind(null);

    Socket client = SocketChannel.open(connector.socket().getLocalSocketAddress()).socket();
    client.setSoTimeout(1000);
    client.setSoLinger(false, -1);
    Socket server = connector.accept().socket();
    server.setSoTimeout(1000);
    server.setSoLinger(false, -1);

    // Write from client to server
    client.getOutputStream().write(1);

    // Server reads
    assertEquals(1, server.getInputStream().read());

    // Write from server to client with oshut
    server.getOutputStream().write(1);
    // System.err.println("OSHUT "+server);
    server.shutdownOutput();

    // Client reads response
    assertEquals(1, client.getInputStream().read());

    try {
      // Client reads -1 and does ishut
      assertEquals(-1, client.getInputStream().read());
      assertFalse(client.isInputShutdown());
      // System.err.println("ISHUT "+client);
      client.shutdownInput();

      // Client ???
      // System.err.println("OSHUT "+client);
      client.shutdownOutput();
      // System.err.println("CLOSE "+client);
      client.close();

      // Server reads -1, does ishut and then close
      assertEquals(-1, server.getInputStream().read());
      assertFalse(server.isInputShutdown());
      // System.err.println("ISHUT "+server);

      try {
        server.shutdownInput();
      } catch (SocketException e) {
        // System.err.println(e);
      }
      // System.err.println("CLOSE "+server);
      server.close();

    } catch (Exception e) {
      System.err.println(e);
      assertTrue(OS.IS_OSX);
    }
  }
示例#28
0
  private void doAccept() throws IOException {
    Socket s = null;
    final long startTime = System.currentTimeMillis();

    while (true) {
      s = ss.accept();
      if (s.getInetAddress().equals(msg.ip)) {
        // got the connection from the right host
        // Close listenning socket.
        ss.close();
        break;
      } else if (ss instanceof SocksServerSocket) {
        // We can't accept more then one connection
        s.close();
        ss.close();
        throw new SocksException(SocksProxyBase.SOCKS_FAILURE);
      } else {
        if (acceptTimeout != 0) { // If timeout is not infinit
          final long passed = System.currentTimeMillis() - startTime;
          final int newTimeout = acceptTimeout - (int) passed;

          if (newTimeout <= 0) {
            throw new InterruptedIOException("newTimeout <= 0");
          }
          ss.setSoTimeout(newTimeout);
        }
        s.close(); // Drop all connections from other hosts
      }
    }

    // Accepted connection
    remote_sock = s;
    remote_in = s.getInputStream();
    remote_out = s.getOutputStream();

    // Set timeout
    remote_sock.setSoTimeout(iddleTimeout);

    final InetAddress inetAddress = s.getInetAddress();
    final int port = s.getPort();
    log.info("Accepted from {}:{}", s.getInetAddress(), port);

    ProxyMessage response;

    if (msg.version == 5) {
      final int cmd = SocksProxyBase.SOCKS_SUCCESS;
      Socks5Message socks5Message = new Socks5Message(cmd, inetAddress, port);
      socks5Message.setDnsResolver(dnsResolver);
      response = socks5Message;
    } else {
      final int cmd = Socks4Message.REPLY_OK;
      Socks4Message socks4Message = new Socks4Message(cmd, inetAddress, port);
      socks4Message.setDnsResolver(dnsResolver);
      response = socks4Message;
    }
    response.write(out);
  }
示例#29
0
  public static void main(String[] args) throws Exception {
    if (args.length == 0) {
      System.err.println("Usage: java PortForward <local-port> <listen-port>");
      return;
    }
    int localPort = Integer.parseInt(args[0]);
    int listenPort = Integer.parseInt(args[1]);
    ServerSocket ss = new ServerSocket(listenPort);
    final Socket in = ss.accept();
    final Socket out = new Socket("127.0.0.1", localPort);

    Thread in2out =
        new Thread() {
          public void run() {
            try {
              InputStream i = in.getInputStream();
              OutputStream o = out.getOutputStream();
              int b = i.read();
              while (b >= 0) {
                o.write((byte) b);
                b = i.read();
              }
              o.close();
              i.close();
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        };
    in2out.start();

    Thread out2in =
        new Thread() {
          public void run() {
            try {
              InputStream i = out.getInputStream();
              OutputStream o = in.getOutputStream();
              int b = i.read();
              while (b >= 0) {
                o.write((byte) b);
                b = i.read();
              }
              o.close();
              i.close();
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        };
    out2in.start();

    in2out.join();
    out2in.join();
    in.close();
    out.close();
  }
示例#30
0
 public static void main(String[] args) {
   boolean sender = false;
   File fi = null;
   try {
     if (args.length == 0) {
       int ret =
           JOptionPane.showConfirmDialog(
               null,
               "Are you the sender? (no = reciever)",
               "Send/Recieve",
               JOptionPane.YES_NO_OPTION);
       JFileChooser chooser = new JFileChooser();
       if (ret == JOptionPane.YES_OPTION) {
         chooser.showOpenDialog(null);
         sender = true;
       } else {
         chooser.showSaveDialog(null);
         sender = false;
       }
       fi = chooser.getSelectedFile();
     } else {
       if (args[0].equalsIgnoreCase("-s")) {
         sender = true;
       } else if (args[0].equalsIgnoreCase("-r")) {
         sender = false;
       }
       fi = new File(args[1]);
     }
   } catch (Exception e) {
     e.printStackTrace();
     exit();
   }
   if (sender && !fi.exists()) {
     System.err.println("Cannot send, file doesn't exist");
     exit();
   }
   try {
     if (sender) {
       ServerSocket ss = new ServerSocket(DEFAULT_PORT);
       Socket sck = ss.accept();
       byte[] hsh = SecureUtils.hash(fi);
       System.out.println(SecureUtils.hexify(hsh));
       sendFile(sck, fi, hsh);
       sck.close();
     } else {
       Socket sck = new Socket("localhost", DEFAULT_PORT);
       byte[] hsh = recvFile(sck, fi);
       System.out.println(SecureUtils.hexify(hsh));
       sck.close();
     }
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }