Example usage for java.net Socket getInputStream

List of usage examples for java.net Socket getInputStream

Introduction

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

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream for this socket.

Usage

From source file:bankingclient.TaoTaiKhoanFrame.java

public TaoTaiKhoanFrame(NewOrOldAccFrame acc) {

    initComponents();/*ww  w.j  ava  2s.c o  m*/
    this.jText_ten_tk.setText("");
    this.jText_sd.setText("");

    this.noAcc = acc;
    this.mainCustomerName = null;
    this.setVisible(false);

    jBt_ht.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (NumberUtils.isNumber(jText_sd.getText()) && (Long.parseLong(jText_sd.getText()) > 0)) {
                try {
                    Socket client = new Socket("113.22.46.207", 6013);
                    DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                    dout.writeByte(3);
                    dout.writeUTF(jText_ten_tk.getText() + "\n" + mainCustomerName + "\n" + jText_sd.getText());
                    dout.flush();
                    DataInputStream din = new DataInputStream(client.getInputStream());
                    byte check = din.readByte();
                    if (check == 1) {
                        JOptionPane.showMessageDialog(rootPane, "da tao tai khoan thanh cong");
                    } else {
                        JOptionPane.showMessageDialog(rootPane, "tao tai khoan khong thanh cong");
                    }
                    client.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                noAcc.setVisible(true);
                TaoTaiKhoanFrame.this.setVisible(false);
            } else {
                JOptionPane.showMessageDialog(rootPane, "Can nhap lai so tien gui");
            }

        }
    });
    jBt_ql.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            noAcc.setVisible(true);
            TaoTaiKhoanFrame.this.setVisible(false);

        }
    });
}

From source file:org.openmrs.module.pacsintegration.component.HL7ListenerComponentTest.java

@Test
public void shouldListenForAndParseORU_R01Message() throws Exception {

    ModuleActivator activator = new PacsIntegrationActivator();
    activator.started();// w  ww .  j  ava 2  s.c  o  m
    Context.getService(PacsIntegrationService.class).initializeHL7Listener();

    List<Patient> patients = patientService.getPatients(null, "101-6",
            Collections.singletonList(emrApiProperties.getPrimaryIdentifierType()), true);
    assertThat(patients.size(), is(1)); // sanity check
    Patient patient = patients.get(0);
    List<Encounter> encounters = encounterService.getEncounters(patient, null, null, null, null,
            Collections.singletonList(radiologyProperties.getRadiologyReportEncounterType()), null, null, null,
            false);
    assertThat(encounters.size(), is(0)); // sanity check

    try {
        String message = "MSH|^~\\&|HMI|Mirebalais Hospital|RAD|REPORTS|20130228174549||ORU^R01|RTS01CE16055AAF5290|P|2.3|\r"
                + "PID|1||101-6||Patient^Test^||19770222|M||||||||||\r" + "PV1|1||||||||||||||||||\r"
                + "OBR|1||0000001297|127689^SOME_X-RAY|||20130228170556||||||||||||MBL^CR||||||F|||||||M123&Goodrich&Mark&&&&||||20130228170556\r"
                + "OBX|1|TX|127689^SOME_X-RAY||Clinical Indication: ||||||F\r";

        Thread.sleep(2000); // give the simple server time to start

        Socket socket = new Socket("127.0.0.1", 6665);

        PrintStream writer = new PrintStream(socket.getOutputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        writer.print(header);
        writer.print(message);
        writer.print(trailer + "\r");
        writer.flush();

        Thread.sleep(2000);

        // confirm that report encounter has been created and has obs (we more thoroughly test the handler in the ORU_R01 handler and Radiology Service (in emr module) tests)
        encounters = encounterService.getEncounters(patient, null, null, null, null,
                Collections.singletonList(radiologyProperties.getRadiologyReportEncounterType()), null, null,
                null, false);
        assertThat(encounters.size(), is(1));
        assertThat(encounters.get(0).getObs().size(), is(4));

        // confirm that the proper ack is sent out
        String response = reader.readLine();
        assertThat(response, containsString("|ACK|"));
    } finally {
        activator.stopped();
    }

}

From source file:org.openmrs.module.pacsintegration.component.HL7ListenerComponentTest.java

@Test
public void shouldListenForAndParseORU_R01MessageMissingProcedureCode() throws Exception {

    ModuleActivator activator = new PacsIntegrationActivator();
    activator.started();/*from   w  ww  .ja  va2 s  . co m*/
    Context.getService(PacsIntegrationService.class).initializeHL7Listener();

    List<Patient> patients = patientService.getPatients(null, "101-6",
            Collections.singletonList(emrApiProperties.getPrimaryIdentifierType()), true);
    assertThat(patients.size(), is(1)); // sanity check
    Patient patient = patients.get(0);
    List<Encounter> encounters = encounterService.getEncounters(patient, null, null, null, null,
            Collections.singletonList(radiologyProperties.getRadiologyReportEncounterType()), null, null, null,
            false);
    assertThat(encounters.size(), is(0)); // sanity check

    try {
        String message = "MSH|^~\\&|HMI|Mirebalais Hospital|RAD|REPORTS|20130228174549||ORU^R01|RTS01CE16055AAF5290|P|2.3|\r"
                + "PID|1||101-6||Patient^Test^||19770222|M||||||||||\r" + "PV1|1||||||||||||||||||\r"
                + "OBR|1||0000001297||||20130228170556||||||||||||MBL^CR||||||F|||||||M123&Goodrich&Mark&&&&||||20130228170556\r"
                + "OBX|1|TX|127689^SOME_X-RAY||Clinical Indication: ||||||F\r";

        Thread.sleep(2000); // give the simple server time to start

        Socket socket = new Socket("127.0.0.1", 6665);

        PrintStream writer = new PrintStream(socket.getOutputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        writer.print(header);
        writer.print(message);
        writer.print(trailer + "\r");
        writer.flush();

        Thread.sleep(2000);

        // confirm that report encounter has been created and has obs (we more thoroughly test the handler in the ORU_R01 handler and Radiology Service (in emr module) tests)
        encounters = encounterService.getEncounters(patient, null, null, null, null,
                Collections.singletonList(radiologyProperties.getRadiologyReportEncounterType()), null, null,
                null, false);
        assertThat(encounters.size(), is(1));
        assertThat(encounters.get(0).getObs().size(), is(3)); // only 3 because no procedure obs

        // confirm that the proper ack is sent out
        String response = reader.readLine();
        assertThat(response, containsString("|ACK|"));
    } finally {
        activator.stopped();
    }

}

From source file:LCModels.MessageTransmitter.java

@Override
public void run() {
    try {//www.jav  a2s  . co  m
        // Socket connects to the ServerSocket, ServerSocket receives a Socket, what? haha//
        //send data as points
        //            Socket s = new Socket(hostname,targetPort);
        //            Socket z = new Socket(hostname, 48500, InetAddress.getByName("127.0.0.1"), targetPort);
        Socket client = new Socket(hostname, targetPort);
        /* Get server's OutputStream */
        OutputStream outToServer = client.getOutputStream();
        /* Get server's DataOutputStream to write/send message */
        DataOutputStream out = new DataOutputStream(outToServer);
        /* Write message to DataOutputStream */
        out.writeUTF(transmitJSON.toString());
        /* Get InputStream to get message from server */
        InputStream inFromServer = client.getInputStream();
        /* Get DataInputStream to read message of server */
        DataInputStream in = new DataInputStream(inFromServer);
        /* Print message received from server */
        System.out.println("Server says..." + in.readUTF());
        client.close();
    } catch (IOException ex) {
        Logger.getLogger(MessageTransmitter.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.openmrs.module.pacsintegration.component.HL7ListenerComponentTest.java

@Test
public void shouldListenForAndParseORM_001Message() throws Exception {

    ModuleActivator activator = new PacsIntegrationActivator();
    activator.started();/*w ww.j a v a  2s . c  o m*/
    Context.getService(PacsIntegrationService.class).initializeHL7Listener();

    List<Patient> patients = patientService.getPatients(null, "101-6",
            Collections.singletonList(emrApiProperties.getPrimaryIdentifierType()), true);
    assertThat(patients.size(), is(1)); // sanity check
    Patient patient = patients.get(0);
    List<Encounter> encounters = encounterService.getEncounters(patient, null, null, null, null,
            Collections.singletonList(radiologyProperties.getRadiologyStudyEncounterType()), null, null, null,
            false);
    assertThat(encounters.size(), is(0)); // sanity check

    try {

        String message = "MSH|^~\\&|HMI||RAD|REPORTS|20130228174643||ORM^O01|RTS01CE16057B105AC0|P|2.3|\r"
                + "PID|1||101-6||Patient^Test^||19770222|M||||||||||\r" + "ORC|\r"
                + "OBR|1||0000001297|127689^SOME_X-RAY|||20130228170350||||||||||||MBL^CR||||||P|||||||&Goodrich&Mark&&&&^||||20130228170350\r"
                + "OBX|1|RP|||||||||F\r" + "OBX|2|TX|EventType^EventType|1|REVIEWED\r"
                + "OBX|3|CN|Technologist^Technologist|1|1435^Duck^Donald\r"
                + "OBX|4|TX|ExamRoom^ExamRoom|1|100AcreWoods\r"
                + "OBX|5|TS|StartDateTime^StartDateTime|1|20111009215317\r"
                + "OBX|6|TS|StopDateTime^StopDateTime|1|20111009215817\r"
                + "OBX|7|TX|ImagesAvailable^ImagesAvailable|1|1\r"
                + "ZDS|2.16.840.1.113883.3.234.1.3.101.1.2.1013.2011.15607503.2^HMI^Application^DICOM\r";

        Thread.sleep(2000); // give the simple server time to start

        Socket socket = new Socket("127.0.0.1", 6665);

        PrintStream writer = new PrintStream(socket.getOutputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        writer.print(header);
        writer.print(message);
        writer.print(trailer + "\r");
        writer.flush();

        Thread.sleep(2000);

        // confirm that study encounter has been created and has obs (we more thoroughly test the handler in the ORU_R01 handler and Radiology Service (in emr module) tests)
        encounters = encounterService.getEncounters(patient, null, null, null, null,
                Collections.singletonList(radiologyProperties.getRadiologyStudyEncounterType()), null, null,
                null, false);
        assertThat(encounters.size(), is(1));
        assertThat(encounters.get(0).getObs().size(), is(3));

        // confirm that the proper ack is sent out
        String response = reader.readLine();
        assertThat(response, containsString("|ACK|"));
    } finally {
        activator.stopped();
    }

}

From source file:io.undertow.server.handlers.HttpTunnelingViaConnectTestCase.java

@Test
public void testConnectViaProxy() throws Exception {

    final HttpHost proxy = new HttpHost(DefaultServer.getHostAddress("default"),
            DefaultServer.getHostPort("default") + 1, "http");
    final HttpHost target = new HttpHost(DefaultServer.getHostAddress("default"),
            DefaultServer.getHostPort("default"), "http");
    ProxyClient proxyClient = new ProxyClient();
    Socket socket = proxyClient.tunnel(proxy, target, new UsernamePasswordCredentials("a", "b"));
    try {/*  w  ww  . java  2  s  . co m*/
        Writer out = new OutputStreamWriter(socket.getOutputStream(), HTTP.DEF_CONTENT_CHARSET);
        out.write("GET / HTTP/1.1\r\n");
        out.write("Host: " + target.toHostString() + "\r\n");
        out.write("Connection: close\r\n");
        out.write("\r\n");
        out.flush();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(socket.getInputStream(), HTTP.DEF_CONTENT_CHARSET));
        String line = null;
        boolean found = false;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
            if (line.equals("MyHeader: MyValue")) {
                found = true;
            }
        }
        Assert.assertTrue(found);
    } finally {
        socket.close();
    }
}

From source file:com.sshtools.daemon.SshServer.java

/**
 *
 *
 * @throws IOException//from w ww.ja v a2 s . co  m
 */
protected void startCommandSocket() throws IOException {
    try {

        /**
         * A potential problem exists here. What happens if the command
         * server socket is dropped for any reason? This will cause the
         * server to stop.
         */
        commandServerSocket = new ServerSocket(
                ((ServerConfiguration) ConfigurationLoader.getConfiguration(ServerConfiguration.class))
                        .getCommandPort(),
                50, InetAddress.getByName("127.0.0.1"));
        Socket client;

        while ((client = commandServerSocket.accept()) != null) {
            log.info("Command request received");

            // Read and process the command
            processCommand(client.getInputStream().read(), client);
            client.close();

            if (shutdown) {
                break;
            }
        }

        commandServerSocket.close();

    } catch (Exception e) {
        if (!shutdown) {
            log.fatal("The command socket failed", e);
        }
    }

}

From source file:org.kjkoster.zapcat.test.ZabbixAgentProtocolTest.java

private void query(int port, String key, byte[] expected) throws IOException {
    final Socket socket = new Socket(InetAddress.getLocalHost(), port);

    final Writer out = new OutputStreamWriter(socket.getOutputStream());
    out.write(key);/*from www  .j  a va  2 s  . c  o  m*/
    out.write('\n');
    out.flush();

    final InputStream in = socket.getInputStream();
    final byte[] buffer = new byte[1024];
    in.read(buffer);
    socket.close();
    System.out.println(new String(buffer));
    assertEquals('Z', buffer[0]);
    assertEquals('B', buffer[1]);
    assertEquals('X', buffer[2]);
    assertEquals('D', buffer[3]);
    assertEquals((byte) 0x01, buffer[4]);
    byte[] actual = Arrays.copyOfRange(buffer, 13, 13 + expected.length);
    assertArrayEquals(expected, actual);
    //        assertTrue(Arrays.equals(expected, actual));
}

From source file:com.symbian.driver.plugins.reboot.Activator.java

/**
 * @param switchState//from   w  w  w . ja  v  a2 s.  c om
 * @throws IOException
 */
private synchronized void switchOp(String switchState) throws IOException {
    LOGGER.log(Level.INFO, "Activator::switchOp");

    // Alternative being "TelnetSwitch"
    if (method.compareToIgnoreCase("PortTalk") == 0)// ATX power
    {
        String state = switchState == "2" ? "OFF" : "ON";
        File hardwareSwitchFile = JarUtils.extractResource(Activator.class, "/resource/HardwareSwitch.exe");
        if (hardwareSwitchFile.isFile()) {
            Process p = Runtime.getRuntime()
                    .exec("cmd.exe /c " + hardwareSwitchFile.getAbsolutePath() + " " + state);
            BufferedReader iBufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String lOutput = null;
            StringBuffer iOutputBuffer = new StringBuffer();
            while ((lOutput = iBufferedReader.readLine()) != null) {
                lOutput += System.getProperty("line.separator");
                iOutputBuffer.append(lOutput);
                // Parse for errors and redirect to appropriate buffer.
            }
            LOGGER.info(iOutputBuffer.toString());
        } else {
            LOGGER.warning(hardwareSwitchFile.getAbsolutePath() + " was not found");
        }
    } else {

        String responseLine = "";
        String[] states = { "User Name :", "Password  :", "Control Console", "Device Manager",
                "Outlet Management", "Outlet Control/Configuration", "Outlet " + outletNo, "Control Outlet",
                "Immediate Off", "Press <ENTER> to continue..." };

        String[] answers = { userName, password, "1", "2", "1", outletNo, "1", switchState, "YES", "\n" };

        Socket sock = new Socket(hostAddr, 23);
        PrintWriter dataToTelnetServer = new PrintWriter(sock.getOutputStream(), true);
        BufferedReader dataFromTelnetServer = new BufferedReader(new InputStreamReader(sock.getInputStream()));
        // start the state machine...
        int state = 0;
        long lastStateChng = System.currentTimeMillis();
        while (state < states.length) {
            while (dataFromTelnetServer.ready()) {
                char nextChar = (char) dataFromTelnetServer.read();
                responseLine += nextChar;
            }
            LOGGER.log(Level.FINE, responseLine);
            if (responseLine.contains(states[state])) // sort of on
            {

                LOGGER.log(Level.FINE, "answers[" + state + "]:" + answers[state]);
                dataToTelnetServer.println(answers[state]);
                state++;
                lastStateChng = System.currentTimeMillis();
                continue;
            }
            if ((System.currentTimeMillis() - lastStateChng) > 10000) {
                // too much time since last change of state...
                // we have lost the connection...
                LOGGER.log(Level.SEVERE, "Lost telnet connection");
                break;
            }
        }
        responseLine = "";
        dataToTelnetServer.flush();
        dataToTelnetServer.close();
        dataFromTelnetServer.close();
        sock.close();
    }
}

From source file:de.ailis.oneinstance.OneInstance.java

/**
 * Opens a client socket to the specified port. If this is successful
 * then the port is returned, otherwise it is closed and null is
 * returned./*from  w  w  w .jav a 2 s  .c o m*/
 * 
 * @param appId
 *            The application ID.
 * @param port
 *            The port number to connect to.
 * @return The client socket or null if no connection to
 *         the server was possible or the server is not the same
 *         application.
 */
private Socket openClientSocket(String appId, int port) {
    try {
        Socket socket = new Socket(InetAddress.getByName(null), port);
        try {
            // Open communication channels
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));

            // Read the appId from the server. Use a one second timeout for
            // this just in case some unresponsive application listens on
            // this port.
            socket.setSoTimeout(1000);
            String serverAppId = in.readLine();
            socket.setSoTimeout(0);

            // Abort if server app ID doesn't match (Or there was none at
            // all)
            if (serverAppId == null || !serverAppId.equals(appId)) {
                socket.close();
                socket = null;
            }

            return socket;
        } catch (IOException e) {
            socket.close();
            return null;
        }
    } catch (IOException e) {
        return null;
    }
}