java.net.SocketException: Connection reset (#8707)

* initial commit

* fix
This commit is contained in:
Pazis 2020-02-11 23:40:59 +03:30 committed by GitHub
parent 7f2de2f176
commit bde0c37075
3 changed files with 108 additions and 0 deletions

View File

@ -0,0 +1,32 @@
package com.baeldung.socketexception;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class SocketClient {
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void startConnection(String ip, int port) throws 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);
return in.readLine();
}
public void stopConnection() throws IOException {
in.close();
out.close();
clientSocket.close();
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.socketexception;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer {
private ServerSocket serverSocket;
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void start(int port) {
try {
serverSocket = new ServerSocket(port);
clientSocket = serverSocket.accept();
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String msg = in.readLine();
if (msg.contains("hi"))
out.println("hi");
else
out.println("didn't understand");
close();
stop();
} catch (IOException e) {
}
}
private void close() throws IOException {
in.close();
out.close();
}
private void stop() throws IOException {
clientSocket.close();
serverSocket.close();
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.socketexception;
import java.io.IOException;
import java.net.SocketException;
import java.util.concurrent.Executors;
import org.junit.BeforeClass;
import org.junit.Test;
public class SocketExceptionHandlingUnitTest {
@BeforeClass
public static void runServer() throws IOException, InterruptedException {
Executors.newSingleThreadExecutor()
.submit(() -> new SocketServer().start(6699));
Thread.sleep(100);
}
@Test
public void givenRunningServer_whenConnectToClosedSocket_thenHandleException() throws IOException {
SocketClient client = new SocketClient();
client.startConnection("127.0.0.1", 6699);
try {
client.sendMessage("hi");
client.sendMessage("hi again");
} catch (SocketException e) {
client.stopConnection();
}
}
}