java - Writing line, reading line, then closing a socket -
i need connect java tcp/ip socket, in order execute few things:
1) read data socket (the optional 'hello' message), discard it;
2) write single line of data, string, socket;
3) read response socket, single line, , store string;
4) close socket;
i wrote code:
public string writelinetosocket(string s) throws ioexception { socket socket = null; outputstreamwriter osw = null; bufferedreader = null; string response = null; try { socket = new socket(serveraddress, serverport); = 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(); } { if (socket!=null) socket.close(); if (osw!=null) osw.close(); } return response; }
for example, using netcat dict.org 2628 have 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 want send command string:
define wn java
finally want store whole response string:
150 1 definitions retrieved 151 "java" wn "wordnet (r) 3.0 (2006)" java n 1: island in indonesia south of borneo; 1 of world's densely populated regions 2: beverage consisting of infusion of ground coffee beans; "he ordered cup of coffee" [syn: {coffee}, {java}] 3: platform-independent object-oriented programming language . 250 ok [d/m/c = 1/0/14; 0.000r 0.000u 0.000s]
my method shows hello message, hangs... doing wrong?
your method called writeline
doesn't write line, unless string has line terminator. add one.
Comments
Post a Comment