Java Socket connection get close with out invoke close connection

Multi tool use
Multi tool use


Java Socket connection get close with out invoke close connection



I have a server and client socket applications as below,


public class ServerApp {

public void start(int port) throws IOException {
serverSocket = new ServerSocket(port);
clientSocket = serverSocket.accept();
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String instr = in.readLine();
//do somethings
out.println("done")
}

public static void main(String args) throws IOException {
ServerApp server = new ServerApp();
server.start(6666);
}
}

public class ClientApp {

public void startConnection(String ip, int port) throws UnknownHostException, IOException {
clientSocket = new Socket(ip, port);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}

public String sendMessage(String msg) throws IOException {
out.println(msg);
String resp = in.readLine();
return resp;
}
}



Unit test class,


public class UnitTest {
@Test
public void testSend() throws UnknownHostException, IOException {
ClientApp client = new ClientApp();
client.startConnection("127.0.0.1", 6666);
String response = client.sendMessage("test msg");
assertEquals("done", response);
}
}



The problem is even when I execute unit test one time, the server connection also get disconnect. I haven not explicitly specify the sockets to be close.



I also want to add below to my test case but only the first execution get success and second one get failed because server connection is disconnected.



@Test(invocationCount = 5, threadPoolSize = 3)





Define 'gets disconnect'. There is nothing here that would detect that.
– EJP
Jul 3 at 2:13




1 Answer
1



Your server accepts only one connection. After responding to the first client, it stops receiving connections. In order to continuously connect to the server, you need to put your accept routine into a loop






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

K6lCmv561OjHtw ih2,E6Ev4K7,O MgA0DJ
y,Zmjrk

Popular posts from this blog

PHP contact form sending but not receiving emails

Do graphics cards have individual ID by which single devices can be distinguished?

Create weekly swift ios local notifications