當前位置: 首頁>>代碼示例>>Java>>正文


Java Socket類代碼示例

本文整理匯總了Java中java.net.Socket的典型用法代碼示例。如果您正苦於以下問題:Java Socket類的具體用法?Java Socket怎麽用?Java Socket使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Socket類屬於java.net包,在下文中一共展示了Socket類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: doPairVerify2

import java.net.Socket; //導入依賴的package包/類
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));
}
 
開發者ID:funtax,項目名稱:AirPlayAuth,代碼行數:27,代碼來源:AirPlayAuth.java

示例2: startSession

import java.net.Socket; //導入依賴的package包/類
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);
	}
}
 
開發者ID:PanagiotisDrakatos,項目名稱:T0rlib4j,代碼行數:19,代碼來源:SocksProxyBase.java

示例3: await

import java.net.Socket; //導入依賴的package包/類
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);
    }
}
 
開發者ID:dryganets,項目名稱:vogar,代碼行數:18,代碼來源:TargetMonitor.java

示例4: assign

import java.net.Socket; //導入依賴的package包/類
/**
 * 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();

}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:26,代碼來源:JIoEndpoint.java

示例5: checkClientTrusted

import java.net.Socket; //導入依賴的package包/類
@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);
}
 
開發者ID:apache,項目名稱:incubator-servicecomb-java-chassis,代碼行數:19,代碼來源:TrustManagerExt.java

示例6: runThread

import java.net.Socket; //導入依賴的package包/類
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();
}
 
開發者ID:limagiran,項目名稱:hearthstone,代碼行數:23,代碼來源:GameServer.java

示例7: openOutputStream

import java.net.Socket; //導入依賴的package包/類
/**
 * 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);
    }
}
 
開發者ID:angcyo,項目名稱:RLibrary,代碼行數:22,代碼來源:WebSocket.java

示例8: bind

import java.net.Socket; //導入依賴的package包/類
/**
 * 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;
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:37,代碼來源:SocketHttpServerConnection.java

示例9: connectSocket

import java.net.Socket; //導入依賴的package包/類
@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);
}
 
開發者ID:aws,項目名稱:aws-sdk-java-v2,代碼行數:21,代碼來源:SdkTlsSocketFactory.java

示例10: await

import java.net.Socket; //導入依賴的package包/類
/**
 * 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);

}
 
開發者ID:c-rainstorm,項目名稱:jerrydog,代碼行數:26,代碼來源:HttpProcessor.java

示例11: main

import java.net.Socket; //導入依賴的package包/類
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");
    }
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:24,代碼來源:ShutdownInput.java

示例12: shutdown

import java.net.Socket; //導入依賴的package包/類
/**
 * 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);
    }
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:29,代碼來源:DefaultClientConnection.java

示例13: connect

import java.net.Socket; //導入依賴的package包/類
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"
	}
}
 
開發者ID:nickbattle,項目名稱:FJ-VDMJ,代碼行數:25,代碼來源:DBGPReader.java

示例14: run

import java.net.Socket; //導入依賴的package包/類
@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);
    }
}
 
開發者ID:ilofX,項目名稱:StazioneMetereologica,代碼行數:20,代碼來源:SocketTCP.java

示例15: run

import java.net.Socket; //導入依賴的package包/類
/**
 * 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();
    }
}
 
開發者ID:wkmeijer,項目名稱:CS4160-trustchain-android,代碼行數:25,代碼來源:Server.java


注:本文中的java.net.Socket類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。