本文整理汇总了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));
}
示例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);
}
}
示例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);
}
}
示例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();
}
示例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);
}
示例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();
}
示例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);
}
}
示例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;
}
示例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);
}
示例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);
}
示例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");
}
}
示例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);
}
}
示例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"
}
}
示例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);
}
}
示例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();
}
}