Dave's Brain

Browse - Programming Tips - How can I do two-way communication on a socket in Java?

Date: 2013mar28
Language: Java
Keywords: TCP/IP

Q.  How can I do two-way communication on a socket in Java?
With a timeout.

A.  Use Java's Socket class like this:

// Helper function private void closeAll(Socket socket, OutputStream out, BufferedReader in) { try { if (out != null) out.close(); if (in != null) in.close(); if (socket != null) socket.close(); // close the socket last } catch (Exception e) { } } boolean socketDialog(final String host, final int port, final int timeoutseconds, final String sendthis) { Socket socket = null; OutputStream os = null; BufferedReader in = null; try { socket = new Socket(); final SocketAddress addr = new InetSocketAddress(host, port); socket.connect(addr, timeoutseconds * 1000); os = socket.getOutputStream(); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); // Send what you want os.write(sendthis.getBytes()); // Now, get the reply String line; while ((line = in.readLine()) != null) { System.out.println("reply: " + line); } closeAll(socket, os, in); } catch (Exception e) { closeAll(socket, os, in); System.out.println("socketDialog problem " + e.toString()); return false; } return true; } void exampleUse() { socketDialog("google.com", 80, 15, "GET /\r\n\r\n"); }

Add a comment

Sign in to add a comment
Copyright © 2008-2018, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.