Java : 소켓의 재 연결은 때때로 오류가 발생합니다
-
21-08-2019 - |
문제
다시 연결을 처리하는 방법을 이해할 수 있도록 프로토 타입 클라이언트 및 서버를 만들고 있습니다. 서버는 서버 소켓을 생성하고 영원히 듣어야합니다. 클라이언트는 연결하고 데이터를 보내고 소켓을 닫을 수 있지만 "I 'm Done and Closing"메시지를 서버에 보내지 않습니다. 이러한 이유로 서버는 a를 가져옵니다 EOFException
그것이 할 때 readByte()
원격 클라이언트가 닫힌 이후. 오류 핸들러에서 EOFException
, 소켓을 닫고 새 소켓을 엽니 다.
여기에 문제가 있습니다. 고객은 때때로 SocketWriteError
그것이 할 때 outputStream.write()
소켓/입력 스트림/외곽선을 성공적으로 엽니다면 호출하십시오. 이 소켓을 열고 닫는 주파수와 관련이있을 수 있습니다. 흥미로운 점 중 하나는 클라이언트가 분쇄하기 전에 임의의 숫자/닫기/재 연결을한다는 것입니다. 때때로 첫 번째 재 연결에서 헛소리를 내며, 다른 경우에는 50 번의 재 연결이 필요합니다. SocketWriteError
.
클라이언트 측의 오류는 다음과 같습니다.
java.net.SocketException: Connection reset by peer: socket write error at java.net.SocketOutputStream.socketWrite0(Native Method) at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92) at java.net.SocketOutputStream.write(SocketOutputStream.java:115) at bytebuffertest.Client.main(Client.java:37)
코드 스 니펫은 다음과 같습니다.
섬기는 사람:
public static void main(String[] args)
{
Server x = new Server();
x.initialize();
}
private void initialize()
{
ServerSocket s;
InputStream is;
DataInputStream dis;
while (true) //ADDED THIS!!!!!!!!!!!!!!!!!!!!!!
{
try
{
s = new ServerSocket(4448);
s.setSoTimeout(0);
s.setReuseAddress(true);
is = s.accept().getInputStream();
System.out.println("accepted client");
dis = new DataInputStream(is);
try
{
byte input = dis.readByte();
System.out.println("read: " + input);
} catch (Exception ex)
{
System.out.println("Exception");
dis.close();
is.close();
s.close();
}
} catch (IOException ex)
{
System.out.println("ioexception");
}
}
}
고객:
public static void main(String[] args)
{
Socket s;
OutputStream os;
try
{
s = new Socket("localhost", 4448);
s.setKeepAlive(true);
s.setReuseAddress(true);
os = s.getOutputStream();
int counter = 0;
while (true)
{
try
{
os.write((byte) counter++);
os.flush();
os.close();
s.close();
s = new Socket("localhost", 4448);
s.setKeepAlive(true);
s.setReuseAddress(true);
os = s.getOutputStream();
} catch (Exception e)
{
e.printStackTrace();
System.err.println("ERROR: reconnecting...");
}
}
} catch (Exception ex)
{
ex.printStackTrace();
System.err.println("ERROR: could not connect");
}
}
누구든지 올바르게 다시 연결하는 방법을 아는 사람이 있습니까?
해결책
오류에서 서버 소켓을 닫지 마십시오.
내가 일반적으로하는 일은 serversocket.accept ()가 소켓을 반환 할 때마다 스레드를 스폰하여 해당 소켓에서 전송 및 수신을 처리합니다. 그렇게하면 누군가가 당신에게 연결하기를 원하자마자 새로운 연결을 수락 할 준비가되었습니다.