Example usage for java.net Socket getOutputStream

List of usage examples for java.net Socket getOutputStream

Introduction

In this page you can find the example usage for java.net Socket getOutputStream.

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream for this socket.

Usage

From source file:edu.vt.middleware.gator.log4j.SocketServerTest.java

/**
 * Tests connecting to the socket server and sending a logging event that
 * should be written to configured appenders.
 *
 * @throws  Exception  On errors.//w ww  .  ja v  a 2 s .c om
 */
@Test
public void testConnectAndLog() throws Exception {
    final Socket sock = new Socket();
    try {
        final SocketAddress addr = new InetSocketAddress(InetAddress.getByName(server.getBindAddress()),
                server.getPort());
        sock.connect(addr, SOCKET_CONNECT_TIMEOUT);

        // Allow the socket server time to build the hierarchy
        // before sending a test logging event
        Thread.sleep(2000);

        Assert.assertEquals(1, server.getLoggingEventHandlers().size());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Sending test logging event.");
        }

        final LoggingEvent event = new LoggingEvent(TEST_CATEGORY, Logger.getLogger(TEST_CATEGORY), Level.DEBUG,
                TEST_MESSAGE, null);
        final ObjectOutputStream oos = new ObjectOutputStream(sock.getOutputStream());
        oos.writeObject(event);
        oos.flush();
    } finally {
        if (sock.isConnected()) {
            sock.close();
        }
    }

    // Pause to allow time for logging events to be written
    Thread.sleep(2000);

    // Client socket close should trigger cleanup of server handler mapping
    Assert.assertEquals(0, server.getLoggingEventHandlers().size());

    for (AppenderConfig appender : testProject.getAppenders()) {
        final String logFilePath = FileHelper.pathCat(CLIENT_ROOT_DIR, testProject.getName(),
                appender.getAppenderParam("file").getValue());
        final String contents = readTextFile(logFilePath);
        Assert.assertTrue(contents.contains(TEST_MESSAGE));
    }
}

From source file:com.fluffypeople.managesieve.ManageSieveClient.java

private void setupAfterConnect(Socket sock) throws IOException {
    sock.setSoTimeout(socketTimeout);//  w ww.j a  v a 2s  .  c  o  m
    byteStream = new BufferedInputStream(sock.getInputStream());
    in = new StreamTokenizer(new InputStreamReader(byteStream, UTF8));
    setupTokenizer();
    out = new PrintWriter(new OutputStreamWriter(sock.getOutputStream()));
}

From source file:com.plotsquared.iserver.core.Worker.java

/**
 * Prepares a request, then calls {@link #handle}
 * @param remote Client socket/*from  ww  w.  j  a v  a 2  s  .  c  o  m*/
 */
private void handle(final Socket remote) {
    // Used for metrics
    final Timer.Context timerContext = Server.getInstance().getMetrics().registerRequestHandling();
    if (CoreConfig.verbose) { // Do we want to output a load of useless information?
        server.log(Message.CONNECTION_ACCEPTED, remote.getInetAddress());
    }
    final BufferedReader input;
    { // Read the actual request
        try {
            input = new BufferedReader(new InputStreamReader(remote.getInputStream()), CoreConfig.Buffer.in);
            output = new BufferedOutputStream(remote.getOutputStream(), CoreConfig.Buffer.out);

            final List<String> lines = new ArrayList<>();
            String str;
            while ((str = input.readLine()) != null && !str.isEmpty()) {
                lines.add(str);
            }

            request = new Request(lines, remote);

            if (request.getQuery().getMethod() == HttpMethod.POST) {
                final int cl = Integer.parseInt(request.getHeader("Content-Length").substring(1));
                request.setPostRequest(PostRequest.construct(request, cl, input));
            }
        } catch (final Exception e) {
            e.printStackTrace();
            return;
        }
    }
    if (!server.silent) {
        server.log(request.buildLog());
    }
    handle();
    timerContext.stop();
}

From source file:com.lithium.flow.shell.sshj.SshjTunnel.java

private void accept(@Nonnull Socket socket) throws IOException {
    log.debug("connection from {}", socket.getRemoteSocketAddress());

    AbstractDirectChannel channel = new AbstractDirectChannel(connection, "direct-tcpip") {
        @Override/*  w  w  w. j  a v  a  2s.c om*/
        @Nonnull
        protected SSHPacket buildOpenReq() {
            return super.buildOpenReq().putString(tunneling.getHost()).putUInt32(tunneling.getPort())
                    .putString(getHost()).putUInt32(server.getLocalPort());
        }
    };
    channel.open();

    socket.setSendBufferSize(channel.getLocalMaxPacketSize());
    socket.setReceiveBufferSize(channel.getRemoteMaxPacketSize());
    Event<IOException> soc2chan = new StreamCopier(socket.getInputStream(), channel.getOutputStream())
            .bufSize(channel.getRemoteMaxPacketSize()).spawnDaemon("soc2chan");
    Event<IOException> chan2soc = new StreamCopier(channel.getInputStream(), socket.getOutputStream())
            .bufSize(channel.getLocalMaxPacketSize()).spawnDaemon("chan2soc");
    SocketStreamCopyMonitor.monitor(5, TimeUnit.SECONDS, soc2chan, chan2soc, channel, socket);
}

From source file:com.tasktop.c2c.server.web.proxy.ajp.AjpProtocol.java

public void forward(HttpServletRequest request, HttpServletResponse response) throws IOException {
    debug(request, "forward");

    Packet packet = new Packet();
    packet.reset();//from  ww  w .  java  2s  .c  om
    // AJP13_FORWARD_REQUEST
    packet.write(Type.REQUEST_FORWARD.code);
    packet.write(computeMethod(request.getMethod()).code);
    packet.write(request.getProtocol());
    packet.write(request.getRequestURI());
    packet.write(request.getRemoteAddr());
    packet.write(request.getRemoteAddr());
    packet.write(request.getServerName());
    packet.write(request.getServerPort());
    packet.write(request.isSecure());

    // request headers
    Map<String, String> headers = new HashMap<String, String>();
    @SuppressWarnings("rawtypes")
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement().toString();
        String headerValue = request.getHeader(headerName);
        headerValue = headerFilter.processRequestHeader(headerName, headerValue);
        if (headerValue != null) {
            headers.put(headerName, headerValue);
        }
    }
    packet.write(headers.size());
    for (Map.Entry<String, String> header : headers.entrySet()) {
        HttpRequestHeader headerType = HttpRequestHeader.fromHeaderName(header.getKey());
        if (headerType != null) {
            packet.write(headerType.code);
        } else {
            packet.write(header.getKey());
        }
        String headerValue = header.getValue();
        packet.write(headerValue == null ? "" : headerValue);
    }

    // request attributes
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        packet.write(Attribute.REMOTE_USER.code);
        packet.write(authentication.getName());
    }

    String queryString = request.getQueryString();
    if (queryString != null) {
        packet.write(Attribute.QUERY_STRING.code);
        packet.write(queryString);
    }

    // packet terminator
    packet.write((byte) 0xff);

    final Object socketKey = new AjpPoolableConnectionFactory.Key(proxyHost, proxyPort);
    Socket connection;

    try {
        connection = allocateSocket(socketKey);
        debug("allocated", connection);
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        throw new RuntimeException(e);
    }

    boolean invalidate = true;
    try {
        OutputStream outputStream = connection.getOutputStream();
        InputStream inputStream = connection.getInputStream();
        packet.write(outputStream);
        packet.reset();

        int bytesWritten = 0;

        int contentLength = request.getContentLength();
        if (contentLength == -1) { // Unknown content length
            contentLength = Integer.MAX_VALUE;
        }
        ServletInputStream requestInput = request.getInputStream();

        OutputStream responseOutput = null;
        boolean reuse = false;

        if (request.getHeader("Content-Length") != null) {
            bytesWritten += processRequestBody(packet, outputStream, bytesWritten, contentLength, requestInput,
                    contentLength);
            debug("sent [" + bytesWritten + "] initial body bytes", connection);
        }

        for (;; packet.reset()) {
            debug("reading packet", connection);
            packet.read(inputStream);

            Type packetType = Type.fromCode(packet.readByte());
            debug("received " + packetType, connection);
            if (packetType == Type.END_RESPONSE) {
                reuse = packet.readBoolean();
                break;
            }
            switch (packetType) {
            case GET_BODY_CHUNK:
                int requestedSize = packet.readInt();
                packet.reset();
                int chunkSize = processRequestBody(packet, outputStream, bytesWritten, contentLength,
                        requestInput, requestedSize);
                bytesWritten += chunkSize;
                debug("sent [" + chunkSize + "] bytes of body chunk", connection);
                break;
            case SEND_HEADERS: {
                response.reset();
                int httpStatusCode = packet.readInt();
                packet.readString(); // status message, not used
                response.setStatus(httpStatusCode);
                int headerCount = packet.readInt();
                for (int x = 0; x < headerCount; ++x) {
                    byte b = packet.readByte();
                    packet.unreadByte();
                    String headerName;
                    if (b == ((byte) 0xA0)) {
                        int headerCode = packet.readInt();
                        headerName = HttpResponseHeader.fromCode(headerCode).headerName;
                    } else {
                        headerName = packet.readString();
                    }
                    String headerValue = packet.readString();
                    headerValue = headerFilter.processResponseHeader(headerName, headerValue);
                    if (headerValue != null) {
                        response.setHeader(headerName, headerValue);
                    }
                }
            }
                break;
            case SEND_BODY_CHUNK:
                if (responseOutput == null) {
                    responseOutput = response.getOutputStream();
                }
                packet.copy(responseOutput);
                break;
            }
        }

        // ORDER DEPENDENCY: this should come last
        invalidate = !reuse;

        if (responseOutput != null) {
            responseOutput.close();
        }
    } finally {
        if (!shareConnections) {
            invalidate = true;
        }
        deallocateSocket(socketKey, connection, invalidate);
        debug("released " + (invalidate ? "invalidate" : "reuse"), connection);
    }
}

From source file:com.cong.chenchong.wifi.manager.ProxyConnector.java

public JSONObject sendRequest(Socket socket, JSONObject request) throws JSONException {
    try {//  ww  w .ja v a  2s  .c  o m
        if (socket == null) {
            // The server is probably shutting down
            // myLog.i("null socket in ProxyConnector.sendRequest()");
            return null;
        } else {
            return sendRequest(socket.getInputStream(), socket.getOutputStream(), request);
        }
    } catch (IOException e) {
        // myLog.i("IOException in proxy sendRequest wrapper: " + e);
        return null;
    }
}

From source file:ch.unifr.pai.twice.widgets.mpproxy.server.JettyProxy.java

public void handleConnect(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String uri = request.getRequestURI();

    String port = "";
    String host = "";

    int c = uri.indexOf(':');
    if (c >= 0) {
        port = uri.substring(c + 1);// w w w .  j a va  2s. c  o m
        host = uri.substring(0, c);
        if (host.indexOf('/') > 0)
            host = host.substring(host.indexOf('/') + 1);
    }

    InetSocketAddress inetAddress = new InetSocketAddress(host, Integer.parseInt(port));

    // if
    // (isForbidden(HttpMessage.__SSL_SCHEME,addrPort.getHost(),addrPort.getPort(),false))
    // {
    // sendForbid(request,response,uri);
    // }
    // else
    {
        InputStream in = request.getInputStream();
        final OutputStream out = response.getOutputStream();

        final Socket socket = new Socket(inetAddress.getAddress(), inetAddress.getPort());

        response.setStatus(200);
        response.setHeader("Connection", "close");
        response.flushBuffer();

        //         try {
        //            Thread copy = new Thread(new Runnable() {
        //               public void run() {
        //                  try {
        IOUtils.copy(socket.getInputStream(), out);
        //                  } catch (IOException e) {
        //                     e.printStackTrace();
        //                  }
        //               }
        //            });
        //            copy.start();
        IOUtils.copy(in, socket.getOutputStream());
        //            copy.join();
        //            copy.join(10000);
        //         }
        //         catch (InterruptedException e) {
        //            e.printStackTrace();
        //         }
    }
}

From source file:com.cbsb.ftpserv.ProxyConnector.java

public JSONObject sendRequest(Socket socket, JSONObject request) throws JSONException {
    try {//from   w  w  w  . j ava 2  s .c om
        if (socket == null) {
            // The server is probably shutting down
            myLog.i("null socket in ProxyConnector.sendRequest()");
            return null;
        } else {
            return sendRequest(socket.getInputStream(), socket.getOutputStream(), request);
        }
    } catch (IOException e) {
        myLog.i("IOException in proxy sendRequest wrapper: " + e);
        return null;
    }
}

From source file:com.hijacker.MainActivity.java

static Socket connect() {
    //Can be called from any thread, blocks until the job is finished
    Socket socket;
    try {//from  w  ww.j a va 2s  .  co  m
        InetAddress ip = Inet4Address.getByName(SERVER);
        socket = new Socket();
        socket.connect(new InetSocketAddress(ip, PORT), 2000);

        PrintWriter in = new PrintWriter(socket.getOutputStream());
        BufferedReader out = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        //Authenticate (receive a string generated by the server, combine it with a stored key and send back the hashcode)
        if (debug)
            Log.d("HIJACKER/connect", "Authenticating with server...");
        String temp = out.readLine() + AUTH_KEY;
        in.print(Integer.toString(temp.hashCode()) + '\n');
        in.flush();

        temp = out.readLine();
        if (temp != null) {
            if (!temp.equals(ANS_POSITIVE))
                return null; //Not authenticated, socket will be closed by the server
        } else
            return null; //Connection closed, probably not authenticated
        if (debug)
            Log.d("HIJACKER/connect", "Authenticated");

        if (deviceID == -1) {
            if (debug)
                Log.d("HIJACKER/connect", "Getting new deviceID...");
            in.print(REQ_NEW_ID + '\n');
            in.flush();

            try {
                deviceID = Long.parseLong(out.readLine());
                if (pref_edit != null) {
                    pref_edit.putLong("deviceID", deviceID);
                    pref_edit.commit();
                }
                if (debug)
                    Log.d("HIJACKER/connect", "New deviceID is " + deviceID);
            } catch (NumberFormatException ignored) {
                if (debug)
                    Log.d("HIJACKER/connect", "deviceID caused NumberFormatException, still -1");
            }
        }
        //String should be: info APP_VERSION_NAME APP_VERSION_CODE ANDROID_VERSION DEVICE_MODEL DEVICE_ID
        in.print(REQ_INFO + " " + versionName + " " + versionCode + " " + Build.VERSION.SDK_INT + " "
                + deviceModel + " " + deviceID + '\n');
        in.flush();
    } catch (IOException e) {
        Log.e("HIJACKER/connect", e.toString());
        return null;
    }
    return socket;
}

From source file:com.cws.esolutions.core.utils.NetworkUtils.java

/**
 * Creates an telnet connection to a target host and port number. Silently
 * succeeds if no issues are encountered, if so, exceptions are logged and
 * re-thrown back to the requestor./*  w  w  w. jav a2 s .c o  m*/
 *
 * If an exception is thrown during the <code>socket.close()</code> operation,
 * it is logged but NOT re-thrown. It's not re-thrown because it does not indicate
 * a connection failure (indeed, it means the connection succeeded) but it is
 * logged because continued failures to close the socket could result in target
 * system instability.
 * 
 * @param hostName - The target host to make the connection to
 * @param portNumber - The port number to attempt the connection on
 * @param timeout - How long to wait for a connection to establish or a response from the target
 * @param object - The serializable object to send to the target
 * @return <code>Object</code> as output from the request
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 */
public static final synchronized Object executeTcpRequest(final String hostName, final int portNumber,
        final int timeout, final Object object) throws UtilityException {
    final String methodName = NetworkUtils.CNAME
            + "#executeTcpRequest(final String hostName, final int portNumber, final int timeout, final Object object) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug(hostName);
        DEBUGGER.debug("portNumber: {}", portNumber);
        DEBUGGER.debug("timeout: {}", timeout);
        DEBUGGER.debug("object: {}", object);
    }

    Socket socket = null;
    Object resObject = null;

    try {
        synchronized (new Object()) {
            if (StringUtils.isEmpty(InetAddress.getByName(hostName).toString())) {
                throw new UnknownHostException("No host was found in DNS for the given name: " + hostName);
            }

            InetSocketAddress socketAddress = new InetSocketAddress(hostName, portNumber);

            socket = new Socket();
            socket.setSoTimeout((int) TimeUnit.SECONDS.toMillis(timeout));
            socket.setSoLinger(false, 0);
            socket.setKeepAlive(false);
            socket.connect(socketAddress, (int) TimeUnit.SECONDS.toMillis(timeout));

            if (!(socket.isConnected())) {
                throw new ConnectException("Failed to connect to host " + hostName + " on port " + portNumber);
            }

            ObjectOutputStream objectOut = new ObjectOutputStream(socket.getOutputStream());

            if (DEBUG) {
                DEBUGGER.debug("ObjectOutputStream: {}", objectOut);
            }

            objectOut.writeObject(object);

            resObject = new ObjectInputStream(socket.getInputStream()).readObject();

            if (DEBUG) {
                DEBUGGER.debug("resObject: {}", resObject);
            }

            PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true);

            pWriter.println(NetworkUtils.TERMINATE_TELNET + NetworkUtils.CRLF);

            pWriter.flush();
            pWriter.close();
        }
    } catch (ConnectException cx) {
        throw new UtilityException(cx.getMessage(), cx);
    } catch (UnknownHostException ux) {
        throw new UtilityException(ux.getMessage(), ux);
    } catch (SocketException sx) {
        throw new UtilityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        throw new UtilityException(iox.getMessage(), iox);
    } catch (ClassNotFoundException cnfx) {
        throw new UtilityException(cnfx.getMessage(), cnfx);
    } finally {
        try {
            if ((socket != null) && (!(socket.isClosed()))) {
                socket.close();
            }
        } catch (IOException iox) {
            // log it - this could cause problems later on
            ERROR_RECORDER.error(iox.getMessage(), iox);
        }
    }

    return resObject;
}