List of usage examples for java.net Socket getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:Main.java
public static void handleClientRequest(Socket socket) { try {/* w w w . j a v a2s . co m*/ BufferedReader socketReader = null; BufferedWriter socketWriter = null; socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); socketWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); String inMsg = null; while ((inMsg = socketReader.readLine()) != null) { System.out.println("Received from client: " + inMsg); String outMsg = inMsg; socketWriter.write(outMsg); socketWriter.write("\n"); socketWriter.flush(); } socket.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:gridool.util.net.SocketUtils.java
public static boolean write(final Socket socket, final byte[] b, final long delay, final int maxRetry) throws IOException { final OutputStream sockout = socket.getOutputStream(); for (int i = 0; i < maxRetry; i++) { try {/*from ww w . jav a 2s . c o m*/ sockout.write(b); sockout.flush(); return true; } catch (IOException e) { if (LOG.isWarnEnabled()) { LOG.warn("Failed to write to socket: " + socket.getRemoteSocketAddress() + " #" + i); } } if (delay > 0) { try { Thread.sleep(delay); } catch (InterruptedException ie) { ; } } } if (LOG.isWarnEnabled()) { LOG.warn("Failed to write to socket: " + socket.getRemoteSocketAddress()); } return false; }
From source file:com.googlecode.jmxtrans.model.output.OpenTSDBWriterTests.java
private static OpenTSDBWriter getOpenTSDBWriter(OutputStream out, List<String> typeNames) throws Exception { GenericKeyedObjectPool<InetSocketAddress, Socket> pool = Mockito.mock(GenericKeyedObjectPool.class); Socket socket = Mockito.mock(Socket.class); Mockito.when(pool.borrowObject(Matchers.any(InetSocketAddress.class))).thenReturn(socket); Mockito.when(socket.getOutputStream()).thenReturn(out); OpenTSDBWriter writer = OpenTSDBWriter.builder().setHost("localhost").setPort(4243).addTypeNames(typeNames) .build();/* www . j a v a 2 s .c o m*/ writer.setPool(pool); return writer; }
From source file:com.sp.Parser.Utils.java
public static synchronized void Send_TCP(Socket s, String JsonFormattedResponse) throws IOException { BufferedWriter outToClient = new BufferedWriter(new OutputStreamWriter(s.getOutputStream(), "UTF-8")); outToClient.write(JsonFormattedResponse); outToClient.flush();//from ww w. ja v a 2s . c o m }
From source file:com.sshtools.daemon.SshDaemon.java
/** * * * @param msg/*from w w w .jav a 2s. c o m*/ * * @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.zack6849.alphabot.api.Utils.java
public static String checkServerStatus(InetAddress i, int port) { String returns = "Error."; try {//from w w w.j a va 2 s . com //wow...i never actually used the port argument? Socket s = new Socket(i, port); DataInputStream SS_BF = new DataInputStream(s.getInputStream()); DataOutputStream d = new DataOutputStream(s.getOutputStream()); d.write(new byte[] { (byte) 0xFE, (byte) 0x01 }); SS_BF.readByte(); short length = SS_BF.readShort(); StringBuilder sb = new StringBuilder(); for (int in = 0; in < length; in++) { char ch = SS_BF.readChar(); sb.append(ch); } String all = sb.toString().trim(); System.out.println(all); String[] args1 = all.split("\u0000"); if (args1[3].contains("")) { returns = "MOTD: " + args1[3].replaceAll("[a-m]", "").replaceAll("[1234567890]", "") + " players: [" + args1[4] + "/" + args1[5] + "]"; } else { returns = "MOTD: " + args1[3] + " players: [" + args1[4] + "/" + args1[5] + "]"; } } catch (UnknownHostException e1) { returns = "the host you specified is unknown. check your settings."; } catch (IOException e1) { returns = "sorry, we couldn't reach this server, make sure that the server is up and has query enabled."; } return returns; }
From source file:com.googlecode.jmxtrans.model.output.GraphiteWriterTests.java
private static GraphiteWriter getGraphiteWriter(OutputStream out, List<String> typeNames) throws Exception { GenericKeyedObjectPool<InetSocketAddress, Socket> pool = mock(GenericKeyedObjectPool.class); Socket socket = mock(Socket.class); when(pool.borrowObject(Matchers.any(InetSocketAddress.class))).thenReturn(socket); when(socket.getOutputStream()).thenReturn(out); GraphiteWriter writer = GraphiteWriter.builder().setHost("localhost").setPort(2003).addTypeNames(typeNames) .build();/*from w w w. j a v a 2s . c o m*/ writer.setPool(pool); return writer; }
From source file:eu.stratosphere.nephele.net.NetUtils.java
/** * Returns OutputStream for the socket. If the socket has an associated * SocketChannel then it returns a {@link SocketOutputStream} with the given timeout. If the socket does not * have a channel, {@link Socket#getOutputStream()} is returned. In the later * case, the timeout argument is ignored and the write will wait until * data is available.<br>/* w ww. j ava2 s. c o m*/ * <br> * Any socket created using socket factories returned by {@link #NetUtils}, * must use this interface instead of {@link Socket#getOutputStream()}. * * @see Socket#getChannel() * @param socket * @param timeout * timeout in milliseconds. This may not always apply. zero * for waiting as long as necessary. * @return OutputStream for writing to the socket. * @throws IOException */ public static OutputStream getOutputStream(Socket socket, long timeout) throws IOException { return (socket.getChannel() == null) ? socket.getOutputStream() : new SocketOutputStream(socket, timeout); }
From source file:SimpleProxyServer.java
/** * runs a single-threaded proxy server on * the specified local port. It never returns. *///from w w w . java2 s . c om public static void runServer(String host, int remoteport, int localport) throws IOException { // Create a ServerSocket to listen for connections with ServerSocket ss = new ServerSocket(localport); final byte[] request = new byte[1024]; byte[] reply = new byte[4096]; while (true) { Socket client = null, server = null; try { // Wait for a connection on the local port client = ss.accept(); final InputStream streamFromClient = client.getInputStream(); final OutputStream streamToClient = client.getOutputStream(); // Make a connection to the real server. // If we cannot connect to the server, send an error to the // client, disconnect, and continue waiting for connections. try { server = new Socket(host, remoteport); } catch (IOException e) { PrintWriter out = new PrintWriter(streamToClient); out.print("Proxy server cannot connect to " + host + ":" + remoteport + ":\n" + e + "\n"); out.flush(); client.close(); continue; } // Get server streams. final InputStream streamFromServer = server.getInputStream(); final OutputStream streamToServer = server.getOutputStream(); // a thread to read the client's requests and pass them // to the server. A separate thread for asynchronous. Thread t = new Thread() { public void run() { int bytesRead; try { while ((bytesRead = streamFromClient.read(request)) != -1) { streamToServer.write(request, 0, bytesRead); streamToServer.flush(); } } catch (IOException e) { } // the client closed the connection to us, so close our // connection to the server. try { streamToServer.close(); } catch (IOException e) { } } }; // Start the client-to-server request thread running t.start(); // Read the server's responses // and pass them back to the client. int bytesRead; try { while ((bytesRead = streamFromServer.read(reply)) != -1) { streamToClient.write(reply, 0, bytesRead); streamToClient.flush(); } } catch (IOException e) { } // The server closed its connection to us, so we close our // connection to our client. streamToClient.close(); } catch (IOException e) { System.err.println(e); } finally { try { if (server != null) server.close(); if (client != null) client.close(); } catch (IOException e) { } } } }
From source file:uk.ac.bbsrc.tgac.miso.integration.util.IntegrationUtils.java
/** * Sends a String message to a given host socket * //w ww . j a v a 2 s. c om * @param socket * of type Socket * @param query * of type String * @return String * @throws IntegrationException * when the socket couldn't be created */ public static String sendMessage(Socket socket, String query) throws IntegrationException { BufferedWriter wr = null; BufferedReader rd = null; try { wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8")); // Send data wr.write(query + "\r\n"); wr.flush(); // Get response rd = new BufferedReader(new InputStreamReader(socket.getInputStream())); String line; StringBuilder sb = new StringBuilder(); while ((line = rd.readLine()) != null) { sb.append(line); } wr.close(); rd.close(); String dirty = sb.toString(); StringBuilder response = new StringBuilder(); int codePoint; int i = 0; while (i < dirty.length()) { codePoint = dirty.codePointAt(i); if ((codePoint == 0x9) || (codePoint == 0xA) || (codePoint == 0xD) || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF))) { response.append(Character.toChars(codePoint)); } i += Character.charCount(codePoint); } return response.toString().replace("\\\n", "").replace("\\\t", ""); } catch (UnknownHostException e) { log.error("Cannot resolve host: " + socket.getInetAddress(), e); throw new IntegrationException(e.getMessage()); } catch (IOException e) { log.error("Couldn't get I/O for the connection to: " + socket.getInetAddress(), e); throw new IntegrationException(e.getMessage()); } finally { try { if (wr != null) { wr.close(); } if (rd != null) { rd.close(); } } catch (Throwable t) { log.error("close socket", t); } } }