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:br.com.i9torpedos.model.service.serverSocket.DSSocketSIM1.java

@Override
public void run() {

    try {/*  ww w .j  av a 2s.  com*/
        while (true) {
            Socket socket = server.accept();
            log.info("Cliente conectado  " + socket.getInetAddress());

            try {

                PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
                printWriter.println(conectou);
                log.info("Sinal de autenticao enviado para o Cliente  " + new Date().toString());

                //Faz verificao no fluxo de entrada do Objeto
                ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());

                try {

                    //faz a leitura do Objeto de entrada
                    Object readObject = objectInputStream.readObject();

                    if (readObject instanceof SendSMSMessage) {

                        try {

                            SendSMSMessage smsMessage = (SendSMSMessage) readObject;

                            // Thread.sleep(random.nextInt(10000));

                            ponte.set(smsMessage);
                            Thread t = new Thread(new ConsumerSendSMSMessage(ponte),
                                    "PONTE_ASYNC_DSSOCKETSIM1");
                            t.start();

                            listaSMS.add(smsMessage);

                            objectInputStream.close();
                            socket.close();

                            if (listaSMS.size() > 0 && !listaSMS.isEmpty()) {

                                DServiceModem1 md1 = new DServiceModem1(listaSMS, 1000);
                                new Thread(md1, "MODEM 1").start();
                                listaSMS.clear();

                            }

                        } catch (InterruptedException ex) {
                            Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }

                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
                }

            } catch (IOException ex) {
                Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    socket.close();
                } catch (IOException ex) {
                    Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            server.close();
        } catch (IOException ex) {
            Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

From source file:com.esri.geoevent.test.tools.RunTcpInBdsOutTest.java

public void send(String server, Integer port, Long numEvents, Integer rate, String data_file) {

    BufferedReader br = null;/*from w  ww. ja  v  a  2 s .  c  o  m*/
    ArrayList<String> lines = new ArrayList<>();
    LocalDateTime st = null;

    try {

        // Read the file into String array
        br = new BufferedReader(new FileReader(data_file));

        String line = null;
        while ((line = br.readLine()) != null) {
            lines.add(line);
        }

        Socket sckt = new Socket(server, port);
        OutputStream os = sckt.getOutputStream();

        Integer cnt = 0;

        st = LocalDateTime.now();

        Double ns_delay = 1000000000.0 / (double) rate;

        long ns = ns_delay.longValue();
        if (ns < 0) {
            ns = 0;
        }

        int i = 0;
        int j = 0;

        while (i < numEvents) {
            i++;
            j++;
            if (j >= lines.size()) {
                j = 0;
            }
            line = lines.get(j) + "\n";

            final long stime = System.nanoTime();

            long etime = 0;
            do {
                etime = System.nanoTime();
            } while (stime + ns >= etime);

            os.write(line.getBytes());
            os.flush();

        }

        LocalDateTime et = LocalDateTime.now();
        if (st != null) {
            et = LocalDateTime.now();

            Duration delta = Duration.between(st, et);

            Double elapsed_seconds = (double) delta.getSeconds() + delta.getNano() / 1000000000.0;

            send_rate = (double) numEvents / elapsed_seconds;
        }

        sckt.close();
        os = null;

    } catch (Exception e) {
        System.err.println(e.getMessage());
        send_rate = -1.0;
    } finally {
        try {
            br.close();
        } catch (Exception e) {
            //
        }

        this.send_rate = send_rate;

    }

}

From source file:org.dcache.srm.client.GsiConnectionSocketFactory.java

private void delegate(Socket socket, HttpClientTransport.Delegation delegation, X509Credential credential)
        throws IOException {
    if (delegation != null) {
        switch (delegation) {
        case SKIP:
            break;
        case NONE:
            socket.getOutputStream().write('0');
            socket.getOutputStream().flush();
            break;
        case LIMITED:
        case FULL:
            socket.getOutputStream().write('D');
            socket.getOutputStream().flush();
            try {
                // read csr
                ASN1InputStream dIn = new ASN1InputStream(socket.getInputStream());
                PKCS10CertificationRequest csr = new PKCS10CertificationRequest(
                        CertificationRequest.getInstance(dIn.readObject()));

                // generate proxy
                ProxyRequestOptions options = new ProxyRequestOptions(credential.getCertificateChain(), csr);
                options.setLimited(delegation == HttpClientTransport.Delegation.LIMITED);
                X509Certificate[] chain = ProxyGenerator.generate(options, credential.getKey());

                // send to server
                socket.getOutputStream().write(chain[0].getEncoded());
                socket.getOutputStream().flush();
            } catch (SignatureException | NoSuchProviderException | CertificateEncodingException
                    | InvalidKeyException | NoSuchAlgorithmException | CertificateParsingException e) {
                throw new IOException("Failed to signed CSR during delegation: " + e.getMessage(), e);
            }//from   ww  w  .ja va2  s . c  om
            break;
        }
    }
}

From source file:com.googlecode.jmxtrans.model.output.GraphiteWriterTests.java

@Test
public void booleanAsNumberWorks() throws Exception {
    File testInput = new File(GraphiteWriterTests.class.getResource("/booleanTest.json").toURI());

    boolean continueOnJsonError = true;

    JsonUtils jsonUtils = JmxTransModule.createInjector(new JmxTransConfiguration())
            .getInstance(JsonUtils.class);
    ImmutableList servers = new ConfigurationParser(jsonUtils).parseServers(of(testInput), continueOnJsonError);

    Result result = new Result(System.currentTimeMillis(), "attributeName", "className", "objDomain", null,
            "typeName", ImmutableMap.of("key", (Object) true));

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    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);

    Server server = ((Server) servers.get(0));
    Query query = server.getQueries().asList().get(0);
    GraphiteWriter writer = (GraphiteWriter) (query.getOutputWriters().get(0));
    writer.setPool(pool);/*from   w  w  w  . ja  va2s . co m*/

    writer.doWrite(server, query, of(result));

    // check that the booleanAsNumber property was picked up from the JSON
    assertThat(out.toString()).startsWith("servers.host_123.objDomain.attributeName.key 1");
}

From source file:ca.farrelltonsolar.classic.PVOutputUploader.java

private boolean doUpload(ChargeController controller) throws InterruptedException, IOException {
    String uploadDateString = controller.uploadDate();
    String SID = controller.getSID();
    String fName = controller.getPVOutputLogFilename();
    if (fName != null && fName.length() > 0 && SID != null && SID.length() > 0) {
        DateTime logDate = PVOutputService.LogDate();
        int numberOfDays = Constants.PVOUTPUT_RECORD_LIMIT;
        if (uploadDateString.length() > 0) {
            DateTime uploadDate = DateTime.parse(uploadDateString, DateTimeFormat.forPattern("yyyy-MM-dd"));
            numberOfDays = Days.daysBetween(uploadDate, logDate).getDays();
        }/*from   w  w w  .j av a  2s .c o  m*/
        numberOfDays = numberOfDays > Constants.PVOUTPUT_RECORD_LIMIT ? Constants.PVOUTPUT_RECORD_LIMIT
                : numberOfDays; // limit to 20 days as per pvOutput limits
        if (numberOfDays > 0) {
            Log.d(getClass().getName(), String.format("PVOutput uploading: %s for %d days on thread: %s", fName,
                    numberOfDays, Thread.currentThread().getName()));
            DateTime now = DateTime.now();
            String UploadDate = DateTimeFormat.forPattern("yyyy-MM-dd").print(now);
            Bundle logs = load(fName);
            float[] mData = logs.getFloatArray(String.valueOf(Constants.CLASSIC_KWHOUR_DAILY_CATEGORY)); // kWh/day
            boolean uploadDateRecorded = false;
            for (int i = 0; i < numberOfDays; i++) {
                logDate = logDate.minusDays(1); // latest log entry is for yesterday
                Socket pvOutputSocket = Connect(pvOutput);
                DataOutputStream outputStream = new DataOutputStream(
                        new BufferedOutputStream(pvOutputSocket.getOutputStream()));
                String dateStamp = DateTimeFormat.forPattern("yyyyMMdd").print(logDate);
                StringBuilder feed = new StringBuilder("GET /service/r2/addoutput.jsp");
                feed.append("?key=");
                feed.append(APIKey);
                feed.append("&sid=");
                feed.append(SID);
                feed.append("&d=");
                feed.append(dateStamp);
                feed.append("&g=");
                String wh = String.valueOf(mData[i] * 100);
                feed.append(wh);
                feed.append("\r\n");
                feed.append("Host: ");
                feed.append(pvOutput);
                feed.append("\r\n");
                feed.append("\r\n");
                String resp = feed.toString();
                outputStream.writeBytes(resp);
                outputStream.flush();
                pvOutputSocket.close();
                if (uploadDateRecorded == false) {
                    controller.setUploadDate(UploadDate);
                    uploadDateRecorded = true;
                }
                Thread.sleep(Constants.PVOUTPUT_RATE_LIMIT); // rate limit
            }
            return true;
        }
    }
    return false;
}

From source file:UniqueInstance.java

/**
 * Envoie un message  l'instance de l'application dj ouverte.
 *///from  w ww. jav  a2s  .c om
private void send() {
    PrintWriter pw = null;
    try {
        /* On se connecte sur la machine locale. */
        Socket socket = new Socket("localhost", port);

        /* On dfinit un PrintWriter pour crire sur la sortie de la socket. */
        pw = new PrintWriter(socket.getOutputStream());

        /* On crit le message sur la socket. */
        pw.write(message);
    } catch (IOException e) {
        Logger.getLogger("UniqueInstance").warning("criture sur flux de sortie de la socket chou.");
    } finally {
        if (pw != null) {
            pw.close();
        }
    }
}

From source file:client.gui.ConnectionDialog.java

public void actionPerformed(final ActionEvent event) {

    String nick = null;/*from   w w  w  .jav a 2 s  . co  m*/
    String host = null;
    int port = 0;

    if (event.getSource() == connect) {
        nick = this.nick.getText();
        host = this.host.getText();
        try {
            port = Integer.parseInt(this.port.getText());
        } catch (NumberFormatException e1) {
            new MyDialog("Port number must be integer").setVisible(true);
            return;
        }
    } else if (event.getSource() == connectDev) {
        nick = generateNick();
        host = "localhost";
        port = 5555;
    } else if (event.getSource() == connectSame) {
        nick = "a";
        host = "localhost";
        port = 5555;
    }

    if (port <= 0) {
        new MyDialog("Port number must be bigger than 0").setVisible(true);
        return;
    }

    Socket socket;
    BufferedReader in;

    try {
        socket = new Socket(host, port);
        GlobalVariables.out = new PrintWriter(socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    } catch (java.net.UnknownHostException e2) {
        new MyDialog("Unknown host").setVisible(true);
        return;
    } catch (IOException e3) {
        new MyDialog("Connection unsuccessful").setVisible(true);
        GlobalVariables.connected = false;
        return;
    } catch (java.lang.IllegalArgumentException e4) {
        new MyDialog("Port number is too big").setVisible(true);
        return;
    }

    System.out.println("Nick: " + nick);

    final JSONArray toSend = new JSONArray();
    try {
        toSend.put(new JSONObject().put("action", "first_connection"));
        toSend.put(new JSONObject().put("nick", nick));
    } catch (JSONException e1) {
        e1.printStackTrace();
    }

    GlobalVariables.daemon = true;
    GlobalVariables.me.setNick(nick);
    GlobalVariables.connect.setEnabled(false);
    GlobalVariables.connected = true;
    setVisible(false);
    GlobalVariables.out.println(toSend);
    Thread thread;
    thread = new ReceivingData(in);
    thread.setDaemon(true);
    thread.start();
}

From source file:com.googlecode.android_scripting.jsonrpc.JsonRpcServer.java

@Override
protected void handleConnection(Socket socket) throws Exception {
    RpcReceiverManager receiverManager = mRpcReceiverManagerFactory.create();
    BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()), 8192);
    PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
    boolean passedAuthentication = false;
    String data;/* w w w.  j a  v a 2 s. c o  m*/
    while ((data = reader.readLine()) != null) {
        Log.v("Received: " + data);
        JSONObject request = new JSONObject(data);
        int id = request.getInt("id");
        String method = request.getString("method");
        JSONArray params = request.getJSONArray("params");

        // First RPC must be _authenticate if a handshake was specified.
        if (!passedAuthentication && mHandshake != null) {
            if (!checkHandshake(method, params)) {
                SecurityException exception = new SecurityException("Authentication failed!");
                send(writer, JsonRpcResult.error(id, exception));
                shutdown();
                throw exception;
            }
            passedAuthentication = true;
            send(writer, JsonRpcResult.result(id, true));
            continue;
        }

        MethodDescriptor rpc = receiverManager.getMethodDescriptor(method);
        if (rpc == null) {
            send(writer, JsonRpcResult.error(id, new RpcError("Unknown RPC.")));
            continue;
        }
        try {
            send(writer, JsonRpcResult.result(id, rpc.invoke(receiverManager, params)));
        } catch (Throwable t) {
            Log.e("Invocation error.", t);
            send(writer, JsonRpcResult.error(id, t));
        }
    }
}

From source file:com.googlecode.jmxtrans.model.output.OpenTSDBWriter.java

@Override
public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception {
    Socket socket = null;
    PrintWriter writer = null;//w  w w.  ja  va  2  s .  c o  m

    try {
        socket = pool.borrowObject(address);
        writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), UTF_8), true);

        for (String formattedResult : messageFormatter.formatResults(results, server)) {
            log.debug("OpenTSDB Message: {}", formattedResult);
            writer.write("put " + formattedResult + "\n");
        }

    } catch (ConnectException e) {
        log.error("Error while connecting to OpenTSDB", e);
    } finally {
        if (writer != null && writer.checkError()) {
            log.error("Error writing to OpenTSDB, clearing OpenTSDB socket pool");
            pool.invalidateObject(address, socket);
        } else {
            pool.returnObject(address, socket);
        }
    }
}

From source file:nacho.tfg.blepresencetracker.MyFirebaseInstanceIDService.java

/**
 * Persist token to third-party servers.
 *
 * Modify this method to associate the user's FCM InstanceID token with any server-side account
 * maintained by your application.//from ww  w  . j  av a 2  s.  c  om
 *
 * @param token The new token.
 */
private void sendRegistrationToServer(String token) {
    // Add custom implementation, as needed.
    Intent intent = new Intent(ACTION_SHOW_TOKEN);
    intent.putExtra("token", token);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

    AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected Boolean doInBackground(String... params) {
            String data = params[0];
            String ip = "192.168.4.1";
            int port = 7777;
            try {
                Socket socket = new Socket(ip, port);
                while (!socket.isConnected()) {

                }

                OutputStream out = socket.getOutputStream();
                PrintWriter output = new PrintWriter(out);

                output.println(data);
                output.flush();
                out.close();
                output.close();

                socket.close();
            } catch (SocketException e) {
                e.printStackTrace();
                return false;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            if (result) {
                SharedPreferences settings = PreferenceManager
                        .getDefaultSharedPreferences(MyFirebaseInstanceIDService.this);
                SharedPreferences.Editor editor = settings.edit();
                editor.putBoolean(getString(R.string.registration_id_sent), true);
                editor.commit();
            } else {
                SharedPreferences settings = PreferenceManager
                        .getDefaultSharedPreferences(MyFirebaseInstanceIDService.this);
                SharedPreferences.Editor editor = settings.edit();
                editor.putBoolean(getString(R.string.registration_id_sent), false);
                editor.commit();
            }
        }
    };

    // Change wifi network to "NodeMCU WiFi"

    String ssid = "";
    WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    if (WifiInfo.getDetailedStateOf(wifiInfo.getSupplicantState()) == NetworkInfo.DetailedState.CONNECTED) {
        ssid = wifiInfo.getSSID();
    }

    if (!ssid.equals("NodeMCU WiFi")) {
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), getString(R.string.toast_connect_NodeMCU),
                        Toast.LENGTH_LONG).show();

            }
        });

    }
}