Example usage for java.net Socket Socket

List of usage examples for java.net Socket Socket

Introduction

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

Prototype

public Socket(InetAddress address, int port) throws IOException 

Source Link

Document

Creates a stream socket and connects it to the specified port number at the specified IP address.

Usage

From source file:com.envirover.spl.SPLGroungControlTest.java

@Test
public void testMTMessagePipeline() {
    System.out.println("MT TEST: Testing MT message pipeline...");

    Socket client = null;//from   www.j  ava2 s  .  c  om
    DataOutputStream out = null;

    try {
        System.out.printf("MT TEST: Connecting to tcp://%s:%d", InetAddress.getLocalHost().getHostAddress(),
                config.getMAVLinkPort());
        System.out.println();

        client = new Socket(InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort());

        System.out.printf("MT TEST: Connected to tcp://%s:%d", InetAddress.getLocalHost().getHostAddress(),
                config.getMAVLinkPort());
        System.out.println();

        out = new DataOutputStream(client.getOutputStream());

        MAVLinkPacket packet = getSamplePacket();
        out.write(packet.encodePacket());
        out.flush();

        System.out.printf("MT TEST: MAVLink message sent: msgid = %d", packet.msgid);
        System.out.println();

        Thread.sleep(5000);

        System.out.println("MT TEST: Complete.");
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (out != null)
                out.close();

            if (client != null)
                client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.apporiented.hermesftp.client.FtpTestClient.java

public String openExtendedPassiveMode() throws IOException {
    sendCommand("EPSV");
    String response = getResponse();

    Pattern pattern = Pattern.compile("^.*\\(\\|\\|\\|([0-9]+)\\|\\).*$");
    Matcher matcher = pattern.matcher(response);
    int port = 0;
    if (matcher.matches()) {
        port = Integer.parseInt(matcher.group(1));
    }// ww  w.  j av  a2 s.c o  m

    resetDataSockets();
    passiveModeSocket = new Socket(server, port);
    return response;
}

From source file:com.mirth.connect.connectors.mllp.MllpMessageReceiver.java

protected Socket createClientSocket(URI uri) throws IOException {
    String host = uri.getHost();//from ww w  . j a  v a  2  s . co m
    InetAddress inetAddress = InetAddress.getByName(host);
    return new Socket(inetAddress, uri.getPort());
}

From source file:dk.netarkivet.viewerproxy.WebProxyTester.java

@Test
public void testKill() throws Exception {
    proxy = new WebProxy(uriResolverMock);
    // Check port in use
    try {//w  ww  . j ava2 s. c  om
        new Socket(InetAddress.getLocalHost(), httpPort);
    } catch (IOException e) {
        fail("Port not in use after starting server");
    }

    // Kill server
    proxy.kill();

    // Check port not in use
    try {
        new Socket(InetAddress.getLocalHost(), httpPort);
        fail("Port still in use after killing server");
    } catch (IOException e) {
        // expected
    }
}

From source file:com.jk.framework.util.FakeRunnable.java

/**
 * Check server./*from w w w .  j  a v a2s  . c o m*/
 *
 * @param host
 *            the host
 * @param port
 *            the port
 * @throws ServerDownException
 *             the server down exception
 */
public static void checkServer(final String host, final int port) throws ServerDownException {
    try {
        new Socket(host, port);
    } catch (final IOException ex) {
        throw new ServerDownException(ex, host, port);
    }
}

From source file:com.yeetor.minitouch.Minitouch.java

private Thread startInitialThread(final String host, final int port) {
    Thread thread = new Thread(new Runnable() {
        @Override/*from  w w w . jav  a  2  s  . c o m*/
        public void run() {
            int tryTime = 200;
            while (true) {
                Socket socket = null;
                byte[] bytes = new byte[256];
                try {
                    socket = new Socket(host, port);
                    InputStream inputStream = socket.getInputStream();
                    OutputStream outputStream = socket.getOutputStream();
                    int n = inputStream.read(bytes);

                    if (n == -1) {
                        Thread.sleep(10);
                        socket.close();
                    } else {
                        minitouchSocket = socket;
                        minitouchOutputStream = outputStream;
                        onStartup(true);
                        break;
                    }
                } catch (Exception ex) {
                    if (socket != null) {
                        try {
                            socket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    continue;
                }
                tryTime--;
                if (tryTime == 0) {
                    onStartup(false);
                    break;
                }
            }
        }
    });
    thread.start();
    return thread;
}

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

/**
 * Test robustness.//from w  ww  . jav  a2s. co m
 * 
 * @throws Exception
 *             When the test failed.
 */
@Test
public void testMissingClose() throws Exception {
    final Agent agent = new org.kjkoster.zapcat.zabbix.ZabbixAgent();
    // give the agent some time to open the port
    Thread.sleep(100);
    final Socket socket = new Socket(InetAddress.getLocalHost(),
            org.kjkoster.zapcat.zabbix.ZabbixAgent.DEFAULT_PORT);

    final Writer out = new OutputStreamWriter(socket.getOutputStream());
    out.write("jmx[foo\n");
    out.flush();

    final InputStream in = socket.getInputStream();
    final byte[] buffer = new byte[1024];
    final int read = in.read(buffer);
    assertEquals(29, read);

    assertEquals('Z', buffer[0]);
    assertEquals('B', buffer[1]);
    assertEquals('X', buffer[2]);
    assertEquals('D', buffer[3]);

    assertEquals('N', buffer[17]);
    assertEquals('O', buffer[18]);
    assertEquals('T', buffer[19]);

    // we'll take the rest for granted...

    socket.close();
    agent.stop();
}

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

@Path("/test4")
@POST/*  ww w  . java 2  s .co  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.flipkart.phantom.runtime.impl.server.netty.handler.mysql.MysqlChannelHandler.java

private InputStream initConnection(ChannelHandlerContext ctx, int flag) throws Exception {

    this.mysqlSocket = new Socket(this.host, this.port);
    /**//from  www.j av  a  2s.co m
    * The application prefers high bandwidth above low
    * latency, and low latency above short connection time
    */
    this.mysqlSocket.setPerformancePreferences(CONNECTION_TIME, LATENCY, BANDWIDTH);
    this.mysqlSocket.setTcpNoDelay(true);
    this.mysqlSocket.setTrafficClass(TC);
    this.mysqlSocket.setKeepAlive(true);

    //LOGGER.info("Connected to mysql server at "+this.host+":"+this.port);
    this.mysqlIn = new BufferedInputStream(this.mysqlSocket.getInputStream(), MYSQL_PACKET_SIZE);
    this.mysqlOut = this.mysqlSocket.getOutputStream();
    return this.mysqlIn;
}