java - How to close a server port after we are done using it? -
note: found similar question here:
how close port after using server sockets
but did not find satisfactory answer there.
here code client program:
package hf; import java.io.*; import java.net.*; public class dailyadviceclient { private static final int chatport = 4242; public static void main(string[] args) { dailyadviceclient client = new dailyadviceclient(); client.go(); } private void go() { try { socket socket = new socket("127.0.0.1",chatport); inputstreamreader inputstream = new inputstreamreader(socket.getinputstream()); bufferedreader bufferedreader = new bufferedreader(inputstream); string advice = bufferedreader.readline(); system.out.println("advice received client today "+advice); bufferedreader.close(); } catch(exception e) { system.out.println("failed connect server"); } } }
and here code server program:
package hf; import java.io.*; import java.net.*; public class dailyadviceserver { private string[] advicelist = {"take smaller bites", "go tight jeans. no not make fat.", "one word: inappropriate", "just today, honest. tell boss *really* think", "you might want rethink haircut."}; private static final int chatport = 4242; public static void main(string[] args) { dailyadviceserver server = new dailyadviceserver(); server.go(); } private void go() { try { serversocket serversocket = new serversocket(chatport); while(true) { socket socket = serversocket.accept(); printwriter writer = new printwriter(socket.getoutputstream()); string advice = gettodaysadvice(); writer.println(advice); writer.close(); } } catch(exception e) { system.out.println("error in establishing connection client"); } } private string gettodaysadvice() { string advice = null; int randomindex = (int) (math.random()*advicelist.length); advice = advicelist[randomindex]; return advice; } }
in application, whenever client program connects server program, receives string contains advice day.
when run
netstat -an
in command prompt of windows computer suggested in 1 of answers in aforementioned link, message port 4242
listening
how close port , make available future re-use?
to rid of listening port have call serversocket.close().
Comments
Post a Comment