Java Code Examples for java.net.Socket

The following are top voted examples for showing how to use java.net.Socket. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: T0rlib4j   File: SocksProxyBase.java   View source code 7 votes vote down vote up
protected void startSession() throws SocksException {
	try {
		if (chainProxy == null) {
			proxySocket = new Socket(proxyIP, proxyPort);
		} else if (proxyIP != null) {
			proxySocket = new SocksSocket(chainProxy, proxyIP, proxyPort);
		} else {
			proxySocket = new SocksSocket(chainProxy, proxyHost, proxyPort);
		}

		in = proxySocket.getInputStream();
		out = proxySocket.getOutputStream();
	} catch (final SocksException se) {
		throw se;
	} catch (final IOException io_ex) {
		throw new SocksException(SOCKS_PROXY_IO_ERROR, "" + io_ex);
	}
}
 
Example 2
Project: vogar   File: TargetMonitor.java   View source code 7 votes vote down vote up
public static TargetMonitor await(int port) {
    try {
        final ServerSocket serverSocket = new ServerSocket(port);
        serverSocket.setSoTimeout(ACCEPT_TIMEOUT_MILLIS);
        serverSocket.setReuseAddress(true);
        final Socket socket = serverSocket.accept();
        return new TargetMonitor(new PrintStream(socket.getOutputStream())) {
            @Override public void close() throws IOException {
                socket.close();
                serverSocket.close();
            }
        };

    } catch (IOException e) {
        throw new RuntimeException("Failed to accept a monitor on localhost:" + port, e);
    }
}
 
Example 3
Project: AirPlayAuth   File: AirPlayAuth.java   View source code 7 votes vote down vote up
private void doPairVerify2(Socket socket, byte[] pairVerify1Response, byte[] randomPrivateKey, byte[] randomPublicKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException, InvalidAlgorithmParameterException, SignatureException {
    byte[] atvPublicKey = Arrays.copyOfRange(pairVerify1Response, 0, 32);
    byte[] sharedSecret = new byte[32];
    Curve25519.curve(sharedSecret, randomPrivateKey, atvPublicKey);

    MessageDigest sha512Digest = MessageDigest.getInstance("SHA-512");
    sha512Digest.update("Pair-Verify-AES-Key".getBytes(StandardCharsets.UTF_8));
    sha512Digest.update(sharedSecret);
    byte[] sharedSecretSha512AesKey = Arrays.copyOfRange(sha512Digest.digest(), 0, 16);

    sha512Digest.update("Pair-Verify-AES-IV".getBytes(StandardCharsets.UTF_8));
    sha512Digest.update(sharedSecret);
    byte[] sharedSecretSha512AesIV = Arrays.copyOfRange(sha512Digest.digest(), 0, 16);

    Cipher aesCtr128Encrypt = Cipher.getInstance("AES/CTR/NoPadding");
    aesCtr128Encrypt.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(sharedSecretSha512AesKey, "AES"), new IvParameterSpec(sharedSecretSha512AesIV));

    aesCtr128Encrypt.update(Arrays.copyOfRange(pairVerify1Response, 32, pairVerify1Response.length));

    EdDSAEngine edDSAEngine = new EdDSAEngine();
    edDSAEngine.initSign(authKey);

    byte[] signature = aesCtr128Encrypt.update(edDSAEngine.signOneShot(AuthUtils.concatByteArrays(randomPublicKey, atvPublicKey)));

    AuthUtils.postData(socket, "/pair-verify", "application/octet-stream", AuthUtils.concatByteArrays(new byte[]{0, 0, 0, 0}, signature));
}
 
Example 4
Project: lams   File: JIoEndpoint.java   View source code 6 votes vote down vote up
/**
 * Process an incoming TCP/IP connection on the specified socket.  Any
 * exception that occurs during processing must be logged and swallowed.
 * <b>NOTE</b>:  This method is called from our Connector's thread.  We
 * must assign it to our own thread so that multiple simultaneous
 * requests can be handled.
 *
 * @param socket TCP socket to process
 */
synchronized void assign(Socket socket) {

    // Wait for the Processor to get the previous Socket
    while (available) {
        try {
            wait();
        } catch (InterruptedException e) {
        }
    }

    // Store the newly available Socket and notify our thread
    this.socket = socket;
    available = true;
    notifyAll();

}
 
Example 5
Project: incubator-servicecomb-java-chassis   File: TrustManagerExt.java   View source code 6 votes vote down vote up
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType,
    Socket socket) throws CertificateException {
  if (!option.isAuthPeer()) {
    return;
  }

  String ip = null;
  if (socket != null && socket.isConnected()
      && socket instanceof SSLSocket) {
    InetAddress inetAddress = socket.getInetAddress();
    if (inetAddress != null) {
      ip = inetAddress.getHostAddress();
    }
  }
  checkTrustedCustom(chain, ip);
  trustManager.checkClientTrusted(chain, authType, socket);
}
 
Example 6
Project: hearthstone   File: GameServer.java   View source code 6 votes vote down vote up
private void runThread(Socket player, BufferedReader entrada, PrintStream saida, String json) {
    new Thread(() -> {
        try {
            saida.flush();
            saida.println(json);
            while (player.isConnected()) {
                String pack = entrada.readLine();
                saida.flush();
                saida.println(pack);
            }
        } catch (Exception ex) {
            saida.flush();
            saida.println(new Pacote(Param.OPONENTE_DESISTIU).getJSon());
            close(entrada);
            close(saida);
            close(player);
            close(player.equals(playerOne) ? playerTwo : playerOne);
        } finally {
            Server.close();
        }
    }).start();
}
 
Example 7
Project: RLibrary   File: WebSocket.java   View source code 6 votes vote down vote up
/**
 * Open the output stream of the WebSocket connection.
 * The stream is used by the writing thread.
 */
private WebSocketOutputStream openOutputStream(Socket socket) throws WebSocketException
{
    try
    {
        // Get the output stream of the socket through which
        // this client sends data to the server.
        return new WebSocketOutputStream(
            new BufferedOutputStream(socket.getOutputStream()));
    }
    catch (IOException e)
    {
        // Failed to get the output stream from the raw socket.
        throw new WebSocketException(
            WebSocketError.SOCKET_OUTPUT_STREAM_FAILURE,
            "Failed to get the output stream from the raw socket: " + e.getMessage(), e);
    }
}
 
Example 8
Project: lams   File: SocketHttpServerConnection.java   View source code 6 votes vote down vote up
/**
 * Binds this connection to the given {@link Socket}. This socket will be
 * used by the connection to send and receive data.
 * <p>
 * This method will invoke {@link #createSessionInputBuffer(Socket, int, HttpParams)}
 * and {@link #createSessionOutputBuffer(Socket, int, HttpParams)} methods
 * to create session input / output buffers bound to this socket and then
 * will invoke {@link #init(SessionInputBuffer, SessionOutputBuffer, HttpParams)}
 * method to pass references to those buffers to the underlying HTTP message
 * parser and formatter.
 * <p>
 * After this method's execution the connection status will be reported
 * as open and the {@link #isOpen()} will return <code>true</code>.
 *
 * @param socket the socket.
 * @param params HTTP parameters.
 * @throws IOException in case of an I/O error.
 */
protected void bind(final Socket socket, final HttpParams params) throws IOException {
    if (socket == null) {
        throw new IllegalArgumentException("Socket may not be null");
    }
    if (params == null) {
        throw new IllegalArgumentException("HTTP parameters may not be null");
    }
    this.socket = socket;

    int buffersize = HttpConnectionParams.getSocketBufferSize(params);

    init(
            createSessionInputBuffer(socket, buffersize, params),
            createSessionOutputBuffer(socket, buffersize, params),
            params);

    this.open = true;
}
 
Example 9
Project: aws-sdk-java-v2   File: SdkTlsSocketFactory.java   View source code 6 votes vote down vote up
@Override
public Socket connectSocket(
        final int connectTimeout,
        final Socket socket,
        final HttpHost host,
        final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress,
        final HttpContext context) throws IOException {
    if (log.isDebugEnabled()) {
        log.debug("Connecting to {}:{}", remoteAddress.getAddress(), remoteAddress.getPort());
    }

    Socket connectedSocket = super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context);

    if (connectedSocket instanceof SSLSocket) {
        return new SdkSslSocket((SSLSocket) connectedSocket);
    }

    return new SdkSocket(connectedSocket);
}
 
Example 10
Project: jerrydog   File: HttpProcessor.java   View source code 6 votes vote down vote up
/**
 * Await a newly assigned Socket from our Connector, or <code>null</code>
 * if we are supposed to shut down.
 */
private synchronized Socket await() {

    // Wait for the Connector to provide a new Socket
    while (!available) {
        try {
            wait();
        } catch (InterruptedException e) {
        }
    }

    // Notify the Connector that we have received this Socket
    Socket socket = this.socket;
    available = false;
    notifyAll();

    if ((debug >= 1) && (socket != null))
        log("  The incoming request has been awaited");

    return (socket);

}
 
Example 11
Project: jdk8u-jdk   File: ShutdownInput.java   View source code 6 votes vote down vote up
public static void main(String args[]) throws Exception {
    InetAddress iaddr = InetAddress.getLocalHost();

    try ( ServerSocket ss = new ServerSocket(0);
          Socket s1 = new Socket(iaddr, ss.getLocalPort());
          Socket s2 = ss.accept() ) {

        test(s1, s2, "Testing NET");
    }

    // check the NIO socket adapter
    try (ServerSocketChannel sc = ServerSocketChannel.open().bind(null);
         SocketChannel s1 = SocketChannel.open(
                 new InetSocketAddress(iaddr, sc.socket().getLocalPort()));
         SocketChannel s2 = sc.accept() ) {

        test(s1.socket(), s2.socket(), "Testing NIO");
    }

    if (failed) {
        throw new RuntimeException("Failed: check output");
    }
}
 
Example 12
Project: lams   File: DefaultClientConnection.java   View source code 6 votes vote down vote up
/**
 * Force-closes this connection.
 * If the connection is still in the process of being open (the method
 * {@link #opening opening} was already called but
 * {@link #openCompleted openCompleted} was not), the associated
 * socket that is being connected to a remote address will be closed.
 * That will interrupt a thread that is blocked on connecting
 * the socket.
 * If the connection is not yet open, this will prevent the connection
 * from being opened.
 *
 * @throws IOException      in case of a problem
 */
@Override
public void shutdown() throws IOException {
    shutdown = true;
    try {
        super.shutdown();
        if (log.isDebugEnabled()) {
            log.debug("Connection " + this + " shut down");
        }
        Socket sock = this.socket; // copy volatile attribute
        if (sock != null)
            sock.close();
    } catch (IOException ex) {
        log.debug("I/O error shutting down connection", ex);
    }
}
 
Example 13
Project: FJ-VDMJ   File: DBGPReader.java   View source code 6 votes vote down vote up
private void connect() throws IOException
{
	if (!connected)
	{
		if (port > 0)
		{
			InetAddress server = InetAddress.getByName(host);
			socket = new Socket(server, port);
			input = socket.getInputStream();
			output = socket.getOutputStream();
		}
		else
		{
			socket = null;
			input = System.in;
			output = System.out;
			separator = ' ';
		}

		connected = true;
		init();
		run();			// New threads wait for a "run -i"
	}
}
 
Example 14
Project: StazioneMetereologica   File: SocketTCP.java   View source code 6 votes vote down vote up
@Override
public void run() {
    try {
            this.s = new Socket(this.ADDRESS, this.PORT);
            DataInputStream in = new DataInputStream(new BufferedInputStream(this.s.getInputStream()));
            DataOutputStream out = new DataOutputStream(new BufferedOutputStream(this.s.getOutputStream()));
            out.write("Dati?".getBytes());
            out.flush();
            byte[] data = new byte[10000];
            in.read(data);
            System.out.println();
            Map<Calendar, Pacchetto> map = DataManager.estraiMappa(data);
        synchronized (this.dm){
            this.dm.setData(map);
        }
    } catch (IOException ex) {
        Logger.getLogger(SocketTCP.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example 15
Project: CS4160-trustchain-android   File: Server.java   View source code 6 votes vote down vote up
/**
 * Starts the serverSocket, in the while loop it starts listening for messages.
 * serverSocket.accept() blocks until a message is received.
 */
@Override
public void run() {
    try {
        serverSocket = new ServerSocket(SocketServerPORT);

        listener.updateLog("Server is waiting for messages...");

        while (running) {
            Socket socket = serverSocket.accept();

            // We have received a message, this could be either a crawl request or a halfblock
            MessageProto.Message message = MessageProto.Message.parseFrom(socket.getInputStream());
            Peer peer = new Peer(null, socket.getInetAddress().getHostAddress(), socket.getPort());
            communication.receivedMessage(message, peer);

        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 16
Project: FireAnt   File: MongoHandler.java   View source code 6 votes vote down vote up
public MongoHandler(Socket client, Request req, MongoClient mongoconn) throws Exception {
    Object obj = JSONValue.parse(req.getContent());
    JSONObject jobj = (JSONObject)obj;
    System.out.println(req.getContent());
    if((database = (String)jobj.get("database")) == null) {
        throw new Exception("Database not specified");
    }
    if((collection = (String)jobj.get("collection")) == null){
        throw new Exception("Collection not specified");
    }
    if((operation = (String)jobj.get("operation")) == null){
        throw new Exception("Operation not specified");
    }
    data = (JSONObject)jobj.get("data");
    this.dbconn = mongoconn;

    mdb = dbconn.getDatabase(database);
    mcollection = mdb.getCollection(collection);
    this.client = client;
}
 
Example 17
Project: V8LogScanner   File: TestScanProfile.java   View source code 6 votes vote down vote up
@Test
public void testLanSerialization() {

    RegExp rgx = new RegExp(EventTypes.EXCP);
    rgx.getFilter(PropTypes.Time).add("23:24");
    rgx.getFilter(PropTypes.Descr).add("test");
    profile.addRegExp(rgx);

    SocketTemplates templates = SocketTemplates.instance();
    ServerSocket server = templates.createServerSocket(Constants.serverPort);
    assertNotNull(server);
    String ip = templates.getHostIP(server);
    Socket client = templates.createClientSocket(ip, Constants.serverPort);
    ObjectOutputStream stream = templates.getOutDataReader(client);
    boolean sent = templates.sendData(stream, profile);

    try {
        server.close();
    } catch (Exception e) {
    }

    assertTrue(sent);
}
 
Example 18
Project: stynico   File: ProxyConnector.java   View source code 6 votes vote down vote up
public JSONObject sendRequest(Socket socket, JSONObject request) 
 throws JSONException
 {
try
{
  if (socket == null)
  {
	// The server is probably shutting down
	//myLog.i("null socket in ProxyConnector.sendRequest()");
	return null;
  }
  else
  {
	return sendRequest(socket.getInputStream(), 
					   socket.getOutputStream(), 
					   request);
  }
}
catch (IOException e)
{
//  myLog.i("IOException in proxy sendRequest wrapper: " + e);
  return null;
}
 }
 
Example 19
Project: T0rlib4Android   File: TorClientSocks4.java   View source code 6 votes vote down vote up
public void Init() throws IOException, InterruptedException {
    if(ctx==null){
        Log.e("TorTest", "Couldn't start Tor!");
        return;
    }
    String fileLocation = "torfiles";
    // Start the Tor Onion Proxy
    AndroidTorRelay node = new  AndroidTorRelay(ctx,fileLocation);
    int hiddenServicePort = 80;
    int localPort = node.getSocksPort();
    String OnionAdress = "xl5rbgygp2wbgdbn.onion";
    String localhost="127.0.0.1";

    Socket clientSocket = Utilities.socks4aSocketConnection(OnionAdress, hiddenServicePort, "127.0.0.1", localPort);

    ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream());
    out.flush();

    out.writeObject("i am workingg");
    out.flush();
}
 
Example 20
Project: buildAPKsSamples   File: ClientSocketHandler.java   View source code 6 votes vote down vote up
@Override
public void run() {
    Socket socket = new Socket();
    try {
        socket.bind(null);
        socket.connect(new InetSocketAddress(mAddress.getHostAddress(),
                WiFiServiceDiscoveryActivity.SERVER_PORT), 5000);
        Log.d(TAG, "Launching the I/O handler");
        chat = new ChatManager(socket, handler);
        new Thread(chat).start();
    } catch (IOException e) {
        e.printStackTrace();
        try {
            socket.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return;
    }
}
 
Example 21
Project: fuck_zookeeper   File: GenerateLoad.java   View source code 6 votes vote down vote up
private static String getMode(String hostPort) throws NumberFormatException, UnknownHostException, IOException {
    String parts[] = hostPort.split(":");
    Socket s = new Socket(parts[0], Integer.parseInt(parts[1]));
    s.getOutputStream().write("stat".getBytes());
    BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
    String line;
    try {
      while((line = br.readLine()) != null) {
        if (line.startsWith("Mode: ")) {
          return line.substring(6);
        }
      }
      return "unknown";
    } finally {
      s.close();
    }
}
 
Example 22
Project: javase   File: Server.java   View source code 6 votes vote down vote up
/**
 * 服务端开始工作的方法
 * 
 * @throws Exception
 */
public void start() throws Exception {
	try {
		/*
		 * ServerSocket提供了一个方法: Socket accept() 该方法是一个阻塞方法,用于监听其打开的
		 * 8088端口,当一个客户端通过该端口与 服务端连接时,accept方法就会解除阻塞 然后创建一个Socket实例并返回。这个
		 * Socket的作用就是与刚刚连上的客户端进行 通讯。
		 */
		while (true) {
			System.out.println("等待客户端连接...");
			Socket socket = server.accept();
			System.out.println("一个客户端连接了!");
			// 启动一个线程来处理该客户端的交互工作
			ClientHandler handler = new ClientHandler(socket);
			Thread t = new Thread(handler);
			t.start();
		}

	} catch (Exception e) {
		System.out.println("服务端运行失败!");
		throw e;
	}
}
 
Example 23
Project: java-performance   File: App1Controller.java   View source code 6 votes vote down vote up
@RequestMapping(value = "/sendTcp")
public String sendTcp(@RequestParam(value = "message") String message) throws IOException {
    try (Socket socket = new Socket("localhost", 8985)) {
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        writer.println(message);
        writer.flush();
        log.info("TCP SENT " + socket.getRemoteSocketAddress() + " [" + message + "]");

        String result = reader.readLine();
        log.info("TCP RECEIVED " + socket.getRemoteSocketAddress() + " [" + result + "]");

        return result;
    }
}
 
Example 24
Project: s-store   File: StreamServer.java   View source code 6 votes vote down vote up
public StreamServer(Socket aClientSocket, RateLimiter rateLimiter, long startTime, int duration,
    BufferedReader dataSource, AtomicInteger consumedTuples, int maxTupels) {

  try {
    _duration = duration;
    _sourceBuffer = dataSource;
    _rateLimiter = rateLimiter;
    _clientSocket = aClientSocket;
    _startTime = startTime;
    _cosumedTuples = consumedTuples;
    _maxTuples = maxTupels;
    _output = new BufferedOutputStream(_clientSocket.getOutputStream());
    this.start();
  } catch (IOException e) {
    System.out.println(e.getMessage());
  }
}
 
Example 25
Project: ZooKeeper   File: GenerateLoad.java   View source code 6 votes vote down vote up
private static String getMode(String hostPort) throws NumberFormatException, UnknownHostException, IOException {
    String parts[] = hostPort.split(":");
    Socket s = new Socket(parts[0], Integer.parseInt(parts[1]));
    s.getOutputStream().write("stat".getBytes());
    BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
    String line;
    try {
      while((line = br.readLine()) != null) {
        if (line.startsWith("Mode: ")) {
          return line.substring(6);
        }
      }
      return "unknown";
    } finally {
      s.close();
    }
}
 
Example 26
Project: Cubes   File: ClientConnectionInitializer.java   View source code 6 votes vote down vote up
public static Socket extractJavaSocket(com.badlogic.gdx.net.Socket gdxSocket) throws IOException {
  if (gdxSocket instanceof NetJavaSocketImpl) {
    try {
      Field f = NetJavaSocketImpl.class.getDeclaredField("socket");
      f.setAccessible(true);
      Socket javaSocket = (java.net.Socket) f.get(gdxSocket);
      if (javaSocket != null) {
        return javaSocket;
      } else {
        throw new NullPointerException();
      }
    } catch (Exception e) {
      throw new IOException("Failed to get java socket", e);
    }
  } else {
    throw new IOException("libGDX socket is not a " + NetJavaSocketImpl.class.getSimpleName());
  }
}
 
Example 27
Project: LoRaWAN-Smart-Parking   File: Util.java   View source code 5 votes vote down vote up
/**
 * Closes {@code socket}, ignoring any checked exceptions. Does nothing if
 * {@code socket} is null.
 */
public static void closeQuietly(Socket socket) {
  if (socket != null) {
    try {
      socket.close();
    } catch (RuntimeException rethrown) {
      throw rethrown;
    } catch (Exception ignored) {
    }
  }
}
 
Example 28
Project: RunMap   File: LogServer.java   View source code 5 votes vote down vote up
public static void main(String []args){
    try {
        ServerSocket serverSocket = new ServerSocket(9090);
        AtomicLong mCountLogs = new AtomicLong(0);
        while (true) {
            System.out.println("start write log"+serverSocket.getLocalSocketAddress().toString());
            Socket socket = serverSocket.accept();
            System.out.println("start write log");
            new Thread(new LogWriter(mCountLogs.getAndDecrement(), socket)).start();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 29
Project: RainServer   File: ThreadConnectionListener.java   View source code 5 votes vote down vote up
@Override
public void run() {
	try {
		ServerSocket ss = new ServerSocket(this.port, this.backlog, this.bindAddress);
		System.out.println("ServerSocket bound to " + ss.getLocalSocketAddress().toString());
		while (this.shouldListen) {
			System.out.println("Listening for client connection on " + ss.getLocalSocketAddress() + " "
					+ this.connectedClients.size());
			Socket client = ss.accept();
			// if we have a filter, check this IP doesn't have too many connections open
			if (this.filter != null) {
				this.verifyThreads(this.connectedClients);
				String IP = client.getInetAddress().getHostAddress();
				String connect = this.filter.shouldAcceptConnection(IP, connectedClients);
				if (connect != null) {
					client.getOutputStream().write(connect.getBytes());
					client.getOutputStream().flush();
					client.close();
					System.out.println("Dropped " + IP + " as: " + connect);
					continue;
				}
			}
			System.out.println("Client connected");
			client.setSoTimeout(this.maxIdleTimeMS);
			ThreadSocketHandler handler = new ThreadSocketHandler(
					client, this.server, this.maxMessageSizeBytes);
			this.connectedClients.add(handler);
			handler.start();
			this.verifyThreads(this.connectedClients);
		}
		ss.close();
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 30
Project: OperatieBRP   File: AnonymousSslSocketFactory.java   View source code 5 votes vote down vote up
/**
 * Create a client socket.
 * @param serviceUrl jmx service url
 * @return client socket
 * @throws IOException if an I/O error occurs when creating the socket
 */
@Override
public Socket createSocket(final JMXServiceURL serviceUrl) throws IOException {
    final SSLSocket baseSslSocket = (SSLSocket) sslContext.getSocketFactory().createSocket(serviceUrl.getHost(),
            serviceUrl.getPort());
    baseSslSocket.setEnabledProtocols(enabledProtocols);
    baseSslSocket.setEnabledCipherSuites(enabledCiphersuites);
    baseSslSocket.setKeepAlive(true);

    LOGGER.log(Level.FINE, "Created client socket");
    return baseSslSocket;
}
 
Example 31
Project: lams   File: JSSESocketFactory.java   View source code 5 votes vote down vote up
public Socket createSocket (InetAddress ifAddress, int port)
    throws IOException
{   
    if (!initialized) init();
    Socket socket = sslProxy.createSocket(ifAddress, port);
    initSocket(socket);
    return socket;
}
 
Example 32
Project: CrypDist   File: Client.java   View source code 5 votes vote down vote up
public void initialization() {

        //Establish a connection with server, get number of active peers and their information.
        try {
            Thread t2 = new ReceiveServerRequest(this);
            t2.start();

            Socket serverConnection = new Socket(swAdr, swPort);
            serverConnection.setSoTimeout(Config.SERVER_TIMEOUT);

            DataInputStream in = new DataInputStream(serverConnection.getInputStream());

            receivePeerList(in);

            //Send itself data to server.
            DataOutputStream out = new DataOutputStream(serverConnection.getOutputStream());
            out.writeInt(heartBeatPort);
            out.writeInt(serverPort);
            out.writeUTF(Config.USER_NAME);
            out.writeUTF(Config.USER_PASS);
            out.flush();

            boolean authenticated = in.readBoolean();
            active = in.readBoolean();
            crypDist.setActive(active);
            int size = in.readInt();
            byte[] key_array = new byte[size];
            in.read(key_array);

            crypDist.setSessionKey(key_array);
            crypDist.setAuthenticated(authenticated);

            serverConnection.close();
        }
        catch(IOException e)
        {
            log.warn("Cannot connect to the server, terminated.");
            log.warn(e);
        }
    }
 
Example 33
Project: Cubes_2   File: ClientConnectionInitializer.java   View source code 5 votes vote down vote up
public static PingResult ping(com.badlogic.gdx.net.Socket gdxSocket) throws Exception {
	Socket javaSocket = extractJavaSocket(gdxSocket);
	DataOutputStream dataOutputStream = new DataOutputStream(javaSocket.getOutputStream());
	Long firstTime = System.currentTimeMillis();
	dataOutputStream.writeByte(1); // 1 is ping
	javaSocket.setSoTimeout(TIMEOUT);
	try {
		DataInputStream dataInputStream = new DataInputStream(javaSocket.getInputStream());
		PingResult pingResult = new PingResult();
		pingResult.serverMajor = dataInputStream.readInt();
		Long secondTime = System.currentTimeMillis();
		pingResult.serverMinor = dataInputStream.readInt();
		pingResult.serverPoint = dataInputStream.readInt();
		pingResult.serverBuild = dataInputStream.readInt();
		pingResult.serverHash = dataInputStream.readUTF();
		int playerNum = dataInputStream.readInt();
		pingResult.players = new String[playerNum];
		for (int i = 0; i < pingResult.players.length; i++) {
			pingResult.players[i] = dataInputStream.readUTF();
		}
		pingResult.ping = (int) (secondTime - firstTime);
		gdxSocket.dispose();
		return pingResult;
	} catch (IOException e) {
		if (e instanceof SocketTimeoutException) {
			throw new IOException("Server did not respond in time", e);
		} else {
			throw e;
		}
	}
}
 
Example 34
Project: T0rlib4Android   File: SocksSocket.java   View source code 5 votes vote down vote up
private void doDirect() throws SocksException {
	try {
		log.debug("IP: {}_{}", remoteIP, remotePort);
		directSock = new Socket(remoteIP, remotePort);
		proxy.out = directSock.getOutputStream();
		proxy.in = directSock.getInputStream();
		proxy.proxySocket = directSock;
		localIP = directSock.getLocalAddress();
		localPort = directSock.getLocalPort();
	} catch (final IOException io_ex) {
		final int errCode = SocksProxyBase.SOCKS_DIRECT_FAILED;
		throw new SocksException(errCode, "Direct connect failed:", io_ex);
	}
}
 
Example 35
Project: lazycat   File: Http11Processor.java   View source code 5 votes vote down vote up
@Override
protected boolean breakKeepAliveLoop(SocketWrapper<Socket> socketWrapper) {
	openSocket = keepAlive;
	// If we don't have a pipe-lined request allow this thread to be
	// used by another connection
	if (inputBuffer.lastValid == 0) {
		return true;
	}
	return false;
}
 
Example 36
Project: rawhttp   File: JavaSample.java   View source code 5 votes vote down vote up
@Test
public void frontPageExample() throws IOException {
    RawHttp rawHttp = new RawHttp();

    RawHttpRequest request = rawHttp.parseRequest(
            "GET /hello.txt HTTP/1.1\r\n" +
                    "User-Agent: curl/7.16.3 libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3\r\n" +
                    "Host: www.example.com\r\n" +
                    "Accept-Language: en, mi");
    Socket socket = new Socket("www.example.com", 80);
    request.writeTo(socket.getOutputStream());

    EagerHttpResponse<?> response = rawHttp.parseResponse(socket.getInputStream()).eagerly();

    // call "eagerly()" in order to download the body
    System.out.println(response.eagerly());

    assertThat(response.getStatusCode(), equalTo(404));
    assertTrue(response.getBody().isPresent());

    File responseFile = Files.createTempFile("rawhttp", ".http").toFile();
    try (FileOutputStream out = new FileOutputStream(responseFile)) {
        response.writeTo(out);
    }

    System.out.printf("Response parsed from file (%s):", responseFile);
    System.out.println(rawHttp.parseResponse(responseFile).eagerly());
}
 
Example 37
Project: AspriseOCR   File: NanoHTTPD.java   View source code 5 votes vote down vote up
private static final void safeClose(Socket socket)
{
	if (socket != null)
	{
		try
		{
			socket.close();
		}
		catch (IOException e)
		{
		}
	}
}
 
Example 38
Project: EasyAppleSyncAdapter   File: SSLSocketFactoryCompat.java   View source code 5 votes vote down vote up
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException {
    Socket ssl = delegate.createSocket(host, port, localHost, localPort);
    if (ssl instanceof SSLSocket) {
        upgradeTLS((SSLSocket) ssl);
    }
    return ssl;
}
 
Example 39
Project: JAVA-   File: ServerInfo.java   View source code 5 votes vote down vote up
/**
* connect to server
* @return connected Socket object
*/
	public Socket connect() throws IOException
	{
		Socket sock = new Socket();
		sock.setReuseAddress(true);
		sock.setSoTimeout(ClientGlobal.g_network_timeout);
		sock.connect(new InetSocketAddress(this.ip_addr, this.port), ClientGlobal.g_connect_timeout);
		return sock;
	}
 
Example 40
Project: FirefoxData-android   File: SSLSocketFactory.java   View source code 5 votes vote down vote up
public Socket connectSocket(
        final int connectTimeout,
        final Socket socket,
        final HttpHost host,
        final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress,
        final HttpContext context) throws IOException {
    Args.notNull(host, "HTTP host");
    Args.notNull(remoteAddress, "Remote address");
    final Socket sock = socket != null ? socket : createSocket(context);
    if (localAddress != null) {
        sock.bind(localAddress);
    }
    try {
        sock.connect(remoteAddress, connectTimeout);
    } catch (final IOException ex) {
        try {
            sock.close();
        } catch (final IOException ignore) {
        }
        throw ex;
    }
    // Setup SSL layering if necessary
    if (sock instanceof SSLSocket) {
        final SSLSocket sslsock = (SSLSocket) sock;
        sslsock.startHandshake();
        verifyHostname(sslsock, host.getHostName());
        return sock;
    } else {
        return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context);
    }
}