0

I need to connect from Java to a tcp/ip socket, in order to execute a few things:

1) read data from the socket (the optional 'hello' message), then discard it;

2) write a single line of data, as a string, to the socket;

3) read the response from the socket, a single line, and store it into a String;

4) close the socket;

I wrote this code:

public String writeLineToSocket(String s) throws IOException {

        Socket socket = null;
        OutputStreamWriter osw = null;
        BufferedReader is = null;
        String response = null;

        try {

            socket = new Socket(serverAddress, serverPort);
            is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            osw = new OutputStreamWriter(socket.getOutputStream(), "UTF-8");

            osw.write(s, 0, s.length());
            osw.flush();

            response = is.readLine();
            System.out.println(response);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket!=null) socket.close();
            if (osw!=null) osw.close();
        }

        return response;
    }

For example, using netcat dict.org 2628 I have a first 'hello' message (I'm not interested in it):

220 pan.alephnull.com dictd 1.12.1/rf on Linux 4.4.0-1-amd64 <42349519.9983.1492182590@pan.alephnull.com>

Then I want to send my command string:

DEFINE wn java

Finally I want to store the whole response into a String:

150 1 definitions retrieved 151 "java" wn "WordNet (r) 3.0 (2006)" Java n 1: an island in Indonesia to the south of Borneo; one of the world's most densely populated regions 2: a beverage consisting of an infusion of ground coffee beans; "he ordered a cup of coffee" [syn: {coffee}, {java}] 3: a platform-independent object-oriented programming language . 250 ok [d/m/c = 1/0/14; 0.000r 0.000u 0.000s]

My method only shows the hello message, then it hangs... what am I doing wrong?

Fabio B.
  • 9,138
  • 25
  • 105
  • 177
  • Highly recommend using a DataFetcher (run in its own thread) to read from your socket: https://sourceforge.net/p/tus/code/HEAD/tree/tjacobs/io/DataFetcher.java – ControlAltDel Apr 14 '17 at 15:17
  • http://stackoverflow.com/questions/5987970/socket-bufferedreader-hangs-at-readline followed by http://stackoverflow.com/questions/5244839/does-bufferedreader-ready-method-ensure-that-readline-method-does-not-return – opensam Apr 14 '17 at 15:18

1 Answers1

1

Your method is called writeLine but it doesn't write a line, unless the string already has a line terminator. Add one.

user207421
  • 305,947
  • 44
  • 307
  • 483