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.mit.scratch.ScratchCloudSession.java

public ScratchCloudSession(final ScratchSession session, final String cloudToken, final int projectID)
        throws ScratchProjectException {
    this.session = session;
    this.cloudToken = cloudToken; // if !work, md5 cloudToken
    this.projectID = projectID;
    this.hashToken = this.MD5(this.getCloudToken());

    Socket socket = null;
    PrintWriter out = null;/*w w  w.j a va2s. com*/
    BufferedReader in = null;

    try {
        socket = new Socket(Scratch.CLOUD_SERVER, Scratch.CLOUD_PORT);
        out = new PrintWriter(socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        this.socket = socket;
        this.out = out;
        this.in = in;

        this.thread = new Thread(() -> {
            while (ScratchCloudSession.this.running) {
                String line = "";
                try {
                    line = ScratchCloudSession.this.in.readLine();
                } catch (final IOException e) {
                    e.printStackTrace();
                }
                if (line != null)
                    if (!line.equals("null") && !line.equals("{}"))
                        ScratchCloudSession.this.handleLine(line);

            }
        });
        this.thread.start();

        this.handshake();
    } catch (final Exception e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    }

}

From source file:SimpleFTP.java

/**
 * Sends a file to be stored on the FTP server. Returns true if the file
 * transfer was successful. The file is sent in passive mode to avoid NAT or
 * firewall problems at the client end./*ww w . j  av  a2s .  c  om*/
 */
public synchronized boolean stor(InputStream inputStream, String filename) throws IOException {

    BufferedInputStream input = new BufferedInputStream(inputStream);

    sendLine("PASV");
    String response = readLine();
    if (!response.startsWith("227 ")) {
        throw new IOException("SimpleFTP could not request passive mode: " + response);
    }

    String ip = null;
    int port = -1;
    int opening = response.indexOf('(');
    int closing = response.indexOf(')', opening + 1);
    if (closing > 0) {
        String dataLink = response.substring(opening + 1, closing);
        StringTokenizer tokenizer = new StringTokenizer(dataLink, ",");
        try {
            ip = tokenizer.nextToken() + "." + tokenizer.nextToken() + "." + tokenizer.nextToken() + "."
                    + tokenizer.nextToken();
            port = Integer.parseInt(tokenizer.nextToken()) * 256 + Integer.parseInt(tokenizer.nextToken());
        } catch (Exception e) {
            throw new IOException("SimpleFTP received bad data link information: " + response);
        }
    }

    sendLine("STOR " + filename);

    Socket dataSocket = new Socket(ip, port);

    response = readLine();
    if (!response.startsWith("125 ")) {
        //if (!response.startsWith("150 ")) {
        throw new IOException("SimpleFTP was not allowed to send the file: " + response);
    }

    BufferedOutputStream output = new BufferedOutputStream(dataSocket.getOutputStream());
    byte[] buffer = new byte[4096];
    int bytesRead = 0;
    while ((bytesRead = input.read(buffer)) != -1) {
        output.write(buffer, 0, bytesRead);
    }
    output.flush();
    output.close();
    input.close();

    response = readLine();
    return response.startsWith("226 ");
}

From source file:gr.iit.demokritos.cru.cpserver.CPServer.java

public void StartCPServer() throws IOException, Exception {
    ServerSocket serversocket = new ServerSocket(port);
    System.out.println("Start CPServer");
    Bookeeper bk = new Bookeeper(this.properties);
    while (true) {
        System.out.println("Inside While");
        Socket connectionsocket = serversocket.accept();
        System.out.println("Inet");
        //InetAddress client = connectionsocket.getInetAddress();

        BufferedReader input = new BufferedReader(new InputStreamReader(connectionsocket.getInputStream()));
        DataOutputStream output = new DataOutputStream(connectionsocket.getOutputStream());

        httpHandler(input, output);/*ww  w.  j a va 2 s  .  c  om*/
    }
}

From source file:com.webkey.Ipc.java

public void comBinAuth(String turl, String postData) {
    readAuthKey();// w w  w  . j  a v a2  s.c  o m
    try {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(_context);
        port = prefs.getString("port", "80");
        Socket s = new Socket("127.0.0.1", Integer.parseInt(port));

        //outgoing stream redirect to socket
        DataOutputStream dataOutputStream = new DataOutputStream(s.getOutputStream());
        byte[] utf = postData.getBytes("UTF-8");
        dataOutputStream.writeBytes("POST /" + authKey + turl + " HTTP/1.1\r\n" + "Host: 127.0.0.1\r\n"
                + "Connection: close\r\n" + "Content-Length: " + Integer.toString(utf.length) + "\r\n\r\n");
        dataOutputStream.write(utf, 0, utf.length);
        dataOutputStream.flush();
        dataOutputStream.close();
        s.close();
    } catch (IOException e1) {
        //e1.printStackTrace();      
    }
    /*
    //         Log.d(TAG,"post data");
    String target = "http://127.0.0.1:"+port+"/"+authKey+turl;
    //Log.d(TAG,target);
    URL url = new URL(target);
    URLConnection conn = url.openConnection();
    // Set connection parameters.
    conn.setDoInput (true);
    conn.setDoOutput (true);
    conn.setUseCaches (false);
    //Make server believe we are form data...
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    DataOutputStream out = new DataOutputStream (conn.getOutputStream ());
    // Write out the bytes of the content string to the stream.
    out.writeBytes(postData);
    out.flush ();
    out.close ();
    // Read response
    BufferedReader in = new BufferedReader (new InputStreamReader(conn.getInputStream ()));
    String temp;
    String response = null;
    while ((temp = in.readLine()) != null){
    response += temp + "\n";
    }
    temp = null;
    in.close ();
    System.out.println("Server response:\n'" + response + "'");
    }catch(Exception e){
    Log.d(TAG,e.toString());
    }
            
    */
}

From source file:dualcontrol.CryptoHandler.java

public void handle(DualControlKeyStoreSession dualControl, Socket socket) throws Exception {
    try {/*from  ww  w  . j  a  v  a2s . com*/
        this.dualControl = dualControl;
        DataInputStream dis = new DataInputStream(socket.getInputStream());
        int length = dis.readShort();
        byte[] bytes = new byte[length];
        dis.readFully(bytes);
        String data = new String(bytes);
        String[] fields = data.split(":");
        String mode = fields[0];
        String alias = fields[1];
        this.dos = new DataOutputStream(socket.getOutputStream());
        if (mode.equals("GETKEY")) {
            if (enableGetKey) {
                SecretKey key = dualControl.loadKey(alias);
                dos.writeUTF(key.getAlgorithm());
                write(key.getEncoded());
            }
        } else {
            cipher(mode, alias, fields[2], fields[3], fields[4]);
        }
    } finally {
        dos.close();
    }
}

From source file:infosistema.openbaas.rest.IntegrationResource.java

@Path("/test4")
@POST/*from  www.  j a v a  2 s.c o  m*/
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response test4(JSONObject inputJsonObj, @Context UriInfo ui, @Context HttpHeaders hh)
        throws IOException {
    String everything = "";
    BufferedReader br = new BufferedReader(new FileReader("/home/aniceto/baas/file2000x2000.txt"));
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append("\n");
            line = br.readLine();
        }
        everything = sb.toString();
    } finally {
        br.close();
    }

    Socket echoSocket = null;
    try {
        echoSocket = new Socket("askme2.cl.infosistema.com", 4005);
        PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);

        //StringBuffer str = new StringBuffer((String) inputJsonObj.get("str"));

        //String s = str.toString();//"/// DEVES COLOCAR AQUI A IMAGEM SERIALIZADA COM Base64";
        String s = everything;
        byte[] c = s.getBytes();
        echoSocket.getOutputStream().write(c);
        out.flush();
        s = "\n";
        c = s.getBytes();
        echoSocket.getOutputStream().write(c);
        out.flush();
        System.out.println("OK");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            echoSocket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    return Response.status(Status.OK).entity("DEL OK").build();
}

From source file:com.bmwcarit.barefoot.matcher.ServerTest.java

private void sendRequest(InetAddress host, int port, JSONArray samples)
        throws InterruptedException, IOException, JSONException {
    int trials = 120;
    int timeout = 500;
    Socket client = null;

    while (client == null || !client.isConnected()) {
        try {//  w  w  w  .j a  va  2  s. com
            client = new Socket(host, port);
        } catch (IOException e) {
            Thread.sleep(timeout);

            if (trials == 0) {
                client.close();
                throw new IOException(e.getMessage());
            } else {
                trials -= 1;
            }
        }
    }

    PrintWriter writer = new PrintWriter(client.getOutputStream());
    BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
    writer.println(samples.toString());
    writer.flush();

    String code = reader.readLine();
    assertEquals("SUCCESS", code);

    String response = reader.readLine();
    client.close();

    MatcherKState state = new MatcherKState(new JSONObject(response),
            new MatcherFactory(ServerControl.getServer().getMap()));

    OutputFormatter output = new GeoJSONOutputFormatter();
    PrintWriter out = new PrintWriter(ServerTest.class.getResource("").getPath() + "ServerTest-matching.json");
    out.println(output.format(null, state));
    out.close();

    assertEquals(samples.length(), state.sequence().size());
}

From source file:com.sshtools.j2ssh.agent.SshAgentConnection.java

SshAgentConnection(KeyStore keystore, Socket socket) throws IOException {
    this.keystore = keystore;
    this.in = socket.getInputStream();
    this.out = socket.getOutputStream();
    this.socket = socket;

    socket.setSoTimeout(5000);//from   w  w w  . ja v  a  2s.  c om
    thread = new Thread(this);
    thread.start();
}

From source file:com.sk89q.craftapi.streaming.StreamingServerClient.java

/**
 * Construct the instance.//from w w  w . j a  v a 2  s .  c  om
 * 
 * @param server
 * @param socket
 */
public StreamingServerClient(StreamingServer server, Socket socket) throws Throwable {
    this.server = server;
    this.socket = socket;

    random = SecureRandom.getInstance("SHA1PRNG");
    challenge = new byte[32];
    random.nextBytes(challenge);

    InputStreamReader inReader = new InputStreamReader(socket.getInputStream(), "utf-8");
    in = new BufferedReader(inReader);
    out = new PrintStream(socket.getOutputStream(), true, "utf-8");
}

From source file:catalina.startup.Catalina.java

/**
 * Stop an existing server instance./* w  ww  .  j a v a 2s  .  co m*/
 */
protected void stop() {

    // Create and execute our Digester
    Digester digester = createStopDigester();
    File file = configFile();
    try {
        InputSource is = new InputSource("file://" + file.getAbsolutePath());
        FileInputStream fis = new FileInputStream(file);
        is.setByteStream(fis);
        digester.push(this);
        digester.parse(is);
        fis.close();
    } catch (Exception e) {
        System.out.println("Catalina.stop: " + e);
        e.printStackTrace(System.out);
        System.exit(1);
    }

    // Stop the existing server
    try {
        Socket socket = new Socket("127.0.0.1", server.getPort());
        OutputStream stream = socket.getOutputStream();
        String shutdown = server.getShutdown();
        for (int i = 0; i < shutdown.length(); i++)
            stream.write(shutdown.charAt(i));
        stream.flush();
        stream.close();
        socket.close();
    } catch (IOException e) {
        System.out.println("Catalina.stop: " + e);
        e.printStackTrace(System.out);
        System.exit(1);
    }

}