List of usage examples for java.net Socket Socket
public Socket()
From source file:org.yamj.core.tools.player.PlayerTools.java
/** * Scan a list of IP addresses for players * * @param baseIpAddress/*from ww w . j av a 2 s. c o m*/ * @param port * @param scanStart * @param scanEnd * @param timeout * @return */ private static List<String> scanForPlayers(String baseIpAddress, int port, int scanStart, int scanEnd, int timeout) { List<String> playerList = new ArrayList<>(); for (int i = (scanStart < 1 ? 1 : scanStart); i <= (scanEnd > 255 ? 255 : scanEnd); i++) { try (Socket mySocket = new Socket()) { String ipToScan = baseIpAddress + i; LOG.debug("Scanning {}", ipToScan); SocketAddress address = new InetSocketAddress(ipToScan, port); mySocket.connect(address, timeout); try (PrintWriter out = new PrintWriter(mySocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(mySocket.getInputStream()))) { out.println("setting"); String fromServer; while ((fromServer = in.readLine()) != null) { if (fromServer.equals(XML_PLAYER_IDENT)) { playerList.add(ipToScan); break; } } } } catch (IOException ex) { LOG.trace("IO error during scan", ex); } } LOG.info("Found {} players: {}", playerList.size(), playerList.toString()); return playerList; }
From source file:com.meidusa.venus.io.network.VenusBIOConnectionFactory.java
public VenusBIOConnection makeObject() throws Exception { Socket socket = new Socket(); InetSocketAddress address = null; if (host == null) { address = new InetSocketAddress(port); } else {//from w ww .j ava2 s . co m address = new InetSocketAddress(host, port); } socket.setSendBufferSize(sendBufferSize * 1024); socket.setReceiveBufferSize(receiveBufferSize * 1024); socket.setTcpNoDelay(tcpNoDelay); socket.setKeepAlive(keepAlive); try { if (soTimeout > 0) { socket.setSoTimeout(soTimeout); } if (coTimeout > 0) { socket.connect(address, coTimeout); } else { socket.connect(address); } } catch (ConnectException e) { throw new ConnectException(e.getMessage() + " " + address.getHostName() + ":" + address.getPort()); } VenusBIOConnection conn = new VenusBIOConnection(socket, TimeUtil.currentTimeMillis()); byte[] bts = conn.read(); HandshakePacket handshakePacket = new HandshakePacket(); handshakePacket.init(bts); AuthenPacket authen = getAuthenticator().createAuthenPacket(handshakePacket); conn.write(authen.toByteArray()); bts = conn.read(); int type = AbstractServicePacket.getType(bts); if (type == PacketConstant.PACKET_TYPE_OK) { if (authenticatorLogger.isInfoEnabled()) { authenticatorLogger.info("authenticated by server=" + host + ":" + port + " success"); } } else if (type == PacketConstant.PACKET_TYPE_ERROR) { ErrorPacket error = new ErrorPacket(); error.init(bts); if (authenticatorLogger.isInfoEnabled()) { authenticatorLogger.info("authenticated by server=" + host + ":" + port + " error={code=" + error.errorCode + ",message=" + error.message + "}"); } throw new AuthenticationException(error.message, error.errorCode); } return conn; }
From source file:dbseer.old.middleware.MiddlewareSocket.java
public synchronized boolean connect(String ip, int port) throws IOException { this.ip = ip; this.port = port; socket = new Socket(); InetSocketAddress address = new InetSocketAddress(ip, port); try {//from ww w.j a v a 2s . c o m socket.connect(address, MIDDLEWARE_CONNECT_TIMEOUT); socket.setSoTimeout(MIDDLEWARE_SOCKET_TIMEOUT); input = new DataInputStream(socket.getInputStream()); output = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream())); isConnected = true; } catch (Exception e) { DBSeerExceptionHandler.handleException(e); return false; } return true; }
From source file:lia.gsi.net.GSIGssSocketFactory.java
/** * @param inetAddress ://from w ww . j a v a 2s.c om * the remote address * @param port : * the remote port * @param doDelegation : * if true, the client credential is delegated * @param fullDelegation : * if doDelegation is set, this parameter specifies the type of delegation (FULL or LIMITED) * @return the GSI-protected socket connected to the remote host * @throws IOException */ public java.net.Socket createSocket(java.net.InetAddress inetAddress, int port, boolean doDelegation, boolean fullDelegation) throws IOException { // raw socket Socket socket = null; try { //override the search path for the CA directory: (GSI-SSHTERM writes in the ~/.globus/certificates so we don;t use this) //1) java X509_CERT_DIR property //2) override with X509_CERT_DIR env var //3) default /etc/grid-security/certificates String x509CertDir = System.getProperty("X509_CERT_DIR"); if (x509CertDir == null) { x509CertDir = System.getenv("X509_CERT_DIR"); if (x509CertDir == null) x509CertDir = "/etc/grid-security/certificates"; System.setProperty("X509_CERT_DIR", x509CertDir); } String x509UserProxy = System.getenv("X509_USER_PROXY"); if (x509UserProxy == null) x509UserProxy = CoGProperties.getDefault().getProxyFile(); System.out.println("Trying " + x509UserProxy); GSSCredential credential = createUserCredential(x509UserProxy); if (credential == null) { throw new IOException("User credential not initialized !"); } logger.info("createSocket() user credential is " + credential.getName()); GSSManager manager = ExtendedGSSManager.getInstance(); org.globus.gsi.gssapi.auth.GSSAuthorization gssAuth = org.globus.gsi.gssapi.auth.HostAuthorization .getInstance(); GSSName targetName = gssAuth.getExpectedName(null, inetAddress.getCanonicalHostName()); ExtendedGSSContext context = (ExtendedGSSContext) manager.createContext(targetName, GSSConstants.MECH_OID, credential, GSSContext.DEFAULT_LIFETIME); context.setOption(GSSConstants.GSS_MODE, GSIConstants.MODE_GSI); context.requestCredDeleg(doDelegation); if (doDelegation) { if (fullDelegation) { context.setOption(GSSConstants.DELEGATION_TYPE, GSIConstants.DELEGATION_TYPE_FULL); } else { context.setOption(GSSConstants.DELEGATION_TYPE, GSIConstants.DELEGATION_TYPE_LIMITED); } } SocketAddress socketAddress = new InetSocketAddress(inetAddress, port); socket = new Socket(); socket.connect(socketAddress, GSI_CONNECT_TIMEOUT); GSIGssSocket gsiSocket = new GSIGssSocket(socket, context); gsiSocket.setUseClientMode(true); gsiSocket.setAuthorization(gssAuth); // Should be GSI_MODE ? gsiSocket.setWrapMode(GssSocket.SSL_MODE); gsiSocket.startHandshake(); socket = gsiSocket; } catch (Throwable e) { if (socket != null) { try { socket.close(); } catch (Exception e1) { logger.debug("Socket is already closed."); } } throw new IOException(e.toString()); } // return the wrapped socket return socket; }
From source file:com.qspin.qtaste.tcom.rlogin.RLogin.java
/** * Reboot the remote host by sending the reboot command and check that * the remote host is not accessible anymore. * @return true if success, false otherwise *//*from w ww . j a v a2 s. c om*/ public boolean reboot() { if (!sendCommand("reboot")) { return false; } // wait 1 second try { Thread.sleep(1000); } catch (InterruptedException ex) { } disconnect(); // check that remote host is not accessible anymore // open a socket without any parameters. It hasn't been binded or connected Socket socket = new Socket(); try { // bind to a local ephemeral port socket.bind(null); socket.connect(new InetSocketAddress(remoteHost, RLoginClient.DEFAULT_PORT), 1); } catch (SocketTimeoutException e) { logger.info("Rebooted host " + remoteHost + " successfully"); return true; } catch (IOException e) { logger.error("Something went wrong while rebooting host:" + remoteHost); return false; } finally { try { socket.close(); } catch (IOException ex) { } socket = null; } // Expected to get an exception as the remote host should not be reachable anymore logger.error("Host " + remoteHost + " did not reboot as expected! Please check that no other rlogin client is connected!"); return false; }
From source file:net.arccotangent.pacchat.net.ConnectionHandler.java
public void run() { try {/* w ww. j a va 2 s. c om*/ String line1 = input.readLine(); switch (line1) { case "101 ping": ch_log.i("Client pinged us, responding with an acknowledgement."); output.write("102 pong"); output.newLine(); output.flush(); output.close(); break; case "302 request key update": ch_log.i("Client is requesting a key update."); KeyUpdate update = new KeyUpdate(ip); KeyUpdateManager.addPendingUpdate(connection_id, update); while (KeyUpdateManager.getUpdate(connection_id).isProcessed()) { try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } boolean accepted = KeyUpdateManager.getUpdate(connection_id).isAccepted(); KeyUpdateManager.completeIncomingUpdate(connection_id, KeyUpdateManager.getUpdate(connection_id)); if (accepted) { ch_log.i("Accepting key update"); try { output.write("303 update"); output.newLine(); output.flush(); String pubkeyB64 = input.readLine(); byte[] pubEncoded = Base64.decodeBase64(pubkeyB64); X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubEncoded); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); output.close(); input.close(); KeyManager.saveKeyByIP(ip, keyFactory.generatePublic(pubSpec)); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { ch_log.e("Error updating sender's key!"); e.printStackTrace(); } } else { ch_log.i("Rejecting key update."); output.write("304 no update"); output.newLine(); output.flush(); output.close(); } break; case "301 getkey": ch_log.i("Client requested our public key, sending."); String pubkeyB64 = Base64.encodeBase64String(Main.getKeypair().getPublic().getEncoded()); output.write(pubkeyB64); output.newLine(); output.flush(); output.close(); break; case "200 encrypted message": //incoming encrypted message ch_log.i("Client sent an encrypted message, attempting verification and decryption."); PrivateKey privkey = Main.getKeypair().getPrivate(); String cryptedMsg = input.readLine() + "\n" + input.readLine() + "\n" + input.readLine(); ch_log.i("Checking for sender's public key."); if (KeyManager.checkIfIPKeyExists(ip)) { ch_log.i("Public key found."); } else { ch_log.i("Public key not found, requesting key from their server."); try { Socket socketGetkey = new Socket(); socketGetkey.connect(new InetSocketAddress(InetAddress.getByName(ip), Server.PORT), 1000); BufferedReader inputGetkey = new BufferedReader( new InputStreamReader(socketGetkey.getInputStream())); BufferedWriter outputGetkey = new BufferedWriter( new OutputStreamWriter(socketGetkey.getOutputStream())); outputGetkey.write("301 getkey"); outputGetkey.newLine(); outputGetkey.flush(); String sender_pubkeyB64 = inputGetkey.readLine(); byte[] pubEncoded = Base64.decodeBase64(sender_pubkeyB64); X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubEncoded); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); outputGetkey.close(); inputGetkey.close(); KeyManager.saveKeyByIP(ip, keyFactory.generatePublic(pubSpec)); } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) { ch_log.e("Error saving sender's key!"); e.printStackTrace(); } } PacchatMessage message = MsgCrypto.decryptAndVerifyMessage(cryptedMsg, privkey, KeyManager.loadKeyByIP(ip)); String msg = message.getMessage(); boolean verified = message.isVerified(); boolean decrypted = message.isDecryptedSuccessfully(); String ANSI_RESET = "\u001B[0m"; String ANSI_CYAN = "\u001B[36m"; String ANSI_BOLD = "\u001B[1m"; if (verified && decrypted) { ch_log.i("Acknowledging message."); output.write("201 message acknowledgement"); output.newLine(); output.flush(); output.close(); System.out.println(ANSI_BOLD + ANSI_CYAN + "-----BEGIN MESSAGE-----" + ANSI_RESET); System.out.println(ANSI_BOLD + ANSI_CYAN + msg + ANSI_RESET); System.out.println(ANSI_BOLD + ANSI_CYAN + "-----END MESSAGE-----" + ANSI_RESET); } else if (!verified && decrypted) { ch_log.w("Notifying client that message authenticity was not verified."); output.write("203 unable to verify"); output.newLine(); output.flush(); output.close(); System.out.println(ANSI_BOLD + ANSI_CYAN + "-----BEGIN MESSAGE-----" + ANSI_RESET); System.out.println(ANSI_BOLD + ANSI_CYAN + msg + ANSI_RESET); System.out.println(ANSI_BOLD + ANSI_CYAN + "-----END MESSAGE-----" + ANSI_RESET); } else if (!verified) { ch_log.w("Notifying client that message could not be decrypted."); output.write("202 unable to decrypt"); output.newLine(); output.flush(); output.close(); } break; case "201 message acknowledgement": ch_log.i("Client sent an invalid message acknowledgement."); output.write("400 invalid transmission header"); output.newLine(); output.flush(); output.close(); case "202 unable to decrypt": ch_log.i("Client sent an invalid 'unable to decrypt' transmission."); output.write("400 invalid transmission header"); output.newLine(); output.flush(); output.close(); case "203 unable to verify": ch_log.i("Client sent an invalid 'unable to verify' transmission."); output.write("400 invalid transmission header"); output.newLine(); output.flush(); output.close(); default: ch_log.i("Client sent an invalid request header: " + line1); output.write("400 invalid transmission header"); output.newLine(); output.flush(); output.close(); break; } } catch (IOException e) { ch_log.e("Error in connection handler " + connection_id); e.printStackTrace(); } }
From source file:cn.edu.zju.acm.onlinejudge.judgeservice.JudgeClientJudgeThread.java
private void process() throws IOException, InterruptedException { this.status = Status.CONNECTING; this.socket = new Socket(); this.socket.setKeepAlive(true); this.socket.setSoTimeout(JudgeClient.READ_TIMEOUT); this.logger.info( "Connecting to " + this.address.getAddress().getCanonicalHostName() + ":" + this.address.getPort()); this.socket.connect(this.address, JudgeClient.CONNECTION_TIMEOUT); this.logger.info("Connected"); this.in = new DataInputStream(this.socket.getInputStream()); this.out = new DataOutputStream(this.socket.getOutputStream()); this.status = Status.RUNNING; try {//from ww w. j av a2 s . co m while (!this.isInterrupted()) { try { this.status = Status.WAITING; if (this.submissionQueueReader == null) { CompoundSubmissionFilter submissionFilter = new CompoundSubmissionFilter(); submissionFilter.add(new SimpleSubmissionFilter( new NegationTest(new LanguageTest(this.client.getSupportedLanguages())), Priority.DENY)); submissionFilter.add(this.submissionFilter); submissionFilter.add(this.client.getSubmissionFilter()); submissionFilter.add(this.client.getService().getSubmissionFilter()); this.submissionQueueReader = this.client.getService().getSubmissionQueue() .getReader(submissionFilter); } // IMPORTANT: set to null here to avoid rejudging this one when queue.poll throws a // PersistenceException this.submission = null; this.submission = this.submissionQueueReader.poll(this); this.client.getService().judgeStart(this.submission); this.status = Status.RUNNING; try { this.judge(this.submission); } catch (JudgeServerErrorException e) { this.logger.error(e); this.submission.setJudgeReply(JudgeReply.JUDGE_INTERNAL_ERROR); } catch (JudgeClientErrorException e) { this.logger.error(e); this.submission.setJudgeReply(JudgeReply.JUDGE_INTERNAL_ERROR); } catch (PersistenceException e) { this.logger.error(e); this.submission.setJudgeReply(JudgeReply.JUDGE_INTERNAL_ERROR); } this.submissionDAO.updateSubmission(this.submission, 1); this.submission.setContent(null); } catch (PersistenceException e) { this.client.getService().judge(this.submission, Priority.HIGH); Thread.sleep(60000); } finally { this.client.getService().judgeDone(this.submission); } } } finally { Utility.closeSocket(this.socket); } }
From source file:gov.hhs.fha.nhinc.lift.proxy.properties.imp.ProducerProxyPropertiesService.java
@Override public Socket getSocketToServerForRequest(LiftConnectionRequestToken request) throws IOException { Socket socket = new Socket(); try {/* w w w . j av a2 s.com*/ String fileServerIP = PropertyAccessor.getProperty(NhincConstants.GATEWAY_PROPERTY_FILE, NhincConstants.LIFT_FILESERVER_IP); String fileServerPort = PropertyAccessor.getProperty(NhincConstants.GATEWAY_PROPERTY_FILE, NhincConstants.LIFT_FILESERVER_PORT); int portNum = Integer.parseInt(fileServerPort); SocketAddress socketAddr = new InetSocketAddress(fileServerIP, portNum); socket.connect(socketAddr); } catch (PropertyAccessException ex) { log.error(ex.getMessage()); } log.debug("Creating socket " + socket.getInetAddress() + ": " + socket.getPort()); return socket; }
From source file:esg.common.Utils.java
public static boolean poke(String host, int port, int timeout) { boolean ret = false; Socket socket = null;/*from w ww . ja v a 2s .c om*/ try { (socket = new Socket()).connect(new InetSocketAddress(java.net.InetAddress.getByName(host), port), timeout); socket.close(); ret = true; } catch (Throwable t) { log.error(t.getMessage()); } finally { try { socket.close(); } catch (Throwable t) { } } return ret; }
From source file:monasca.api.integration.docker.ITInfluxDBTest.java
private void waitForPortReady(String host, int port) { System.out.println("waiting to connect to host [" + host + "] on port [" + port + "]"); Socket s = null;//from w ww. j a v a 2 s. co m boolean isPortReady = false; int tryCount = 0; while (!isPortReady) { if (tryCount >= MAX_CONNECT_PORT_TRIES) { System.err.println("Failed to connect to host [" + host + "] on port [" + port + "] in " + "[" + tryCount + "] tries"); tearDown(); System.exit(-1); } try { s = new Socket(); s.setReuseAddress(true); SocketAddress sa = new InetSocketAddress(host, port); s.connect(sa, 50000); isPortReady = true; System.out.println( "Took " + tryCount + " tries to connect to host [" + host + "] on port" + "[" + port + "]"); } catch (Exception e) { tryCount++; } } if (s != null) { try { s.close(); } catch (Exception e) { System.err.print(e); } } }