List of usage examples for java.net Socket Socket
public Socket(InetAddress address, int port) throws IOException
From source file:org.psit.transwatcher.TransWatcher.java
@Override public void run() { try {/* www . j a va 2 s . co m*/ while (true) { String cardIP = connectAndGetCardIP(); if (cardIP != null) { notifyMessage("Found SD card, IP: " + cardIP); // handshake successful, open permanent TCP connection // to listen to new images Socket newImageListenerSocket = null; try { newImageListenerSocket = new Socket(cardIP, 5566); newImageListenerSocket.setKeepAlive(true); InputStream is = newImageListenerSocket.getInputStream(); byte[] c = new byte[1]; byte[] singleMessage = new byte[255]; int msgPointer = 0; startConnectionKeepAliveWatchDog(newImageListenerSocket); startImageDownloaderQueue(cardIP); setState(State.LISTENING); // loop to wait for new images while (newImageListenerSocket.isConnected()) { if (is.read(c) == 1) { if (0x3E == c[0]) { // > // start of filename msgPointer = 0; } else if (0x00 == c[0]) { // end of filename String msg = new String(Arrays.copyOfRange(singleMessage, 0, msgPointer)); notifyMessage("Image shot: " + msg); // add to download queue queue.add(msg); } else { // single byte. add to buffer singleMessage[msgPointer++] = c[0]; } } } setState(State.SEARCHING_CARD); } catch (IOException e) { notifyMessage("Error during image notification connection!"); } finally { try { newImageListenerSocket.close(); } catch (Exception e) { e.printStackTrace(); } } } else { notifyMessage("No card found, retrying."); } Thread.sleep(2000); } } catch (InterruptedException e) { stopImageDownLoaderQueue(); notifyMessage("Connection abandoned."); } }
From source file:it.anyplace.sync.client.protocol.rp.RelayClient.java
public RelayConnection openConnectionSessionMode(final SessionInvitation sessionInvitation) throws Exception { logger.debug("connecting to relay = {}:{} (session mode)", sessionInvitation.getAddress(), sessionInvitation.getPort()); final Socket socket = new Socket(sessionInvitation.getAddress(), sessionInvitation.getPort()); RelayDataInputStream in = new RelayDataInputStream(socket.getInputStream()); RelayDataOutputStream out = new RelayDataOutputStream(socket.getOutputStream()); try {//ww w. j av a 2s . co m { logger.debug("sending join session request, session key = {}", sessionInvitation.getKey()); byte[] key = BaseEncoding.base16().decode(sessionInvitation.getKey()); int lengthOfKey = key.length; out.writeHeader(JOIN_SESSION_REQUEST, 4 + lengthOfKey); out.writeInt(lengthOfKey); out.write(key); out.flush(); } { logger.debug("reading relay response"); MessageReader messageReader = in.readMessage(); checkArgument(messageReader.getType() == RESPONSE); Response response = messageReader.readResponse(); logger.debug("response = {}", response); checkArgument(response.getCode() == RESPONSE_SUCCESS_CODE, "response code = %s (%s) expected %s", response.getCode(), response.getMessage(), RESPONSE_SUCCESS_CODE); logger.debug("relay connection ready"); } return new RelayConnection() { @Override public Socket getSocket() { return socket; } @Override public boolean isServerSocket() { return sessionInvitation.isServerSocket(); } }; } catch (Exception ex) { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); IOUtils.closeQuietly(socket); throw ex; } }
From source file:io.undertow.server.security.SimpleConfidentialRedirectTestCase.java
@ProxyIgnore public void testRedirectWithFullURLInPath() throws IOException { DefaultServer.isProxy();/* w ww . j a v a 2 s . c o m*/ //now we need to test what happens if the client send a full URI //see UNDERTOW-874 try (Socket socket = new Socket(DefaultServer.getHostAddress(), DefaultServer.getHostPort())) { socket.getOutputStream().write(("GET " + DefaultServer.getDefaultServerURL() + "/foo HTTP/1.0\r\n\r\n") .getBytes(StandardCharsets.UTF_8)); String result = FileUtils.readFile(socket.getInputStream()); Assert.assertTrue(result.contains("Location: " + DefaultServer.getDefaultServerSSLAddress() + "/foo")); } }
From source file:com.pavlovmedia.oss.osgi.gelf.impl.GelfLogSink.java
private synchronized void ensureConnection() { if (null == transport) { try {/*from w w w . j av a2 s . c o m*/ InetAddress address = InetAddress.getByName(hostname); transport = new Socket(address, port); transport.shutdownInput(); readerService.addLogListener(this); } catch (IOException e) { if (consoleMessages) { System.err.println( String.format("Failed to connect to %s:%d => %s", hostname, port, e.getMessage())); e.printStackTrace(); } transport = null; } } }
From source file:com.juick.android.WsClient.java
public boolean connect(String host, int port, String location, String headers) { try {//w w w . j a v a 2 s .c o m sock = new Socket(host, port); sock.setSoTimeout(15000); is = sock.getInputStream(); os = sock.getOutputStream(); String handshake = "GET " + location + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: Upgrade\r\n" + "Upgrade: websocket\r\n" + "Origin: " + getOrigin() + "\r\n" + "User-Agent: JuickAdvanced\r\n" + "Sec-WebSocket-Key: SomeKey\r\n" + "Sec-WebSocket-Version: 13\r\n" + "Pragma: no-cache\r\n" + "Cache-Control: no-cache\r\n"; if (headers != null) { handshake += headers; } handshake += "\r\n"; os.write(handshake.getBytes()); return true; } catch (Exception e) { System.err.println(e); //e.printStackTrace(); return false; } }
From source file:com.sshtools.daemon.SshDaemon.java
/** * * * @param msg/* w w w . j av a 2s. c om*/ * * @throws IOException */ public static void stop(String msg) throws IOException { try { Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), ((ServerConfiguration) ConfigurationLoader.getConfiguration(ServerConfiguration.class)) .getCommandPort()); // Write the command id socket.getOutputStream().write(0x3a); // Write the length of the message (max 255) int len = (msg.length() <= 255) ? msg.length() : 255; socket.getOutputStream().write(len); // Write the message if (len > 0) { socket.getOutputStream().write(msg.substring(0, len).getBytes()); } socket.close(); } catch (IOException ioe) { ioe.printStackTrace(); } }
From source file:com.edmunds.etm.agent.impl.TcpHealthCheck.java
protected boolean connectToServer() { InetAddress addr = getHostAddress(); boolean connected; try {//w w w . j a v a 2 s . c o m Socket socket = new Socket(addr, port); socket.close(); connected = true; } catch (IOException e) { connected = false; } if (logger.isDebugEnabled()) { String message = String.format("Connected to server with result: %b", connected); logger.debug(message); } return connected; }
From source file:mpv5.utils.http.HttpClient.java
/** * Runs a GET request/*from www .j a v a 2 s . c om*/ * @param srequest The request, eg /servlets-examples/servlet/RequestInfoExample" * @return * @throws UnknownHostException * @throws IOException * @throws HttpException */ public HttpResponse request(String srequest) throws UnknownHostException, IOException, HttpException { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, params); BasicHttpRequest request = new BasicHttpRequest("GET", srequest); Log.Debug(this, ">> Request URI: " + request.getRequestLine().getUri()); request.setParams(params); httpexecutor.preProcess(request, httpproc, context); HttpResponse response = httpexecutor.execute(request, conn, context); response.setParams(params); httpexecutor.postProcess(response, httpproc, context); // Log.Debug(this, "<< Response: " + response.getStatusLine()); // Log.Debug(this, EntityUtils.toString(response.getEntity())); // Log.Debug(this, "=============="); // if (!connStrategy.keepAlive(response, context)) { // conn.close(); // } else { // Log.Debug(this, "Connection kept alive..."); // } // } else { // Log.Debug(this, "Connection already closed."); return response; } return null; }
From source file:org.freewheelschedule.freewheel.controlserver.ControlThread.java
private void runJob(String hostname, Job jobToRun) throws IOException { log.debug("Connecting to the RemoteWorker to run a command"); Socket remoteWorker = new Socket(jobToRun.getExecutingServer().getName(), jobToRun.getExecutingServer().getPort().intValue()); PrintWriter command = new PrintWriter(remoteWorker.getOutputStream(), true); BufferedReader result = new BufferedReader(new InputStreamReader(remoteWorker.getInputStream())); if (workerAwaitingCommand(result, command, hostname) && jobToRun instanceof CommandJob) { if (!sendCommandToExecute(jobToRun, result, command)) { log.error("Job not queued properly"); } else {/*from w ww. j ava 2s. com*/ log.error("Unexpected response from RemoteClient"); } } }
From source file:com.seajas.search.utilities.rmi.RestrictedHostSocketFactory.java
/** * Create a new client socket.//w ww. j a v a2 s . c o m * * @param host * @param port * @return Socket * @throws IOException */ @Override public Socket createSocket(final String host, final int port) throws IOException { if (logger.isInfoEnabled()) logger.info("Creating (client-side) socket #" + totalSocketsCreated.incrementAndGet() + " to host '" + host + "' and port " + port); return new Socket(host, port); }