我写了一个简单的服务器和客户端示例,如下所示。
客户:
获取输入流并从流中读取。此时获得例外
public class DateServer {
public static void main(String[] args) throws InterruptedException {
ServerSocket serverSocket = null;
Socket client = null;
try {
serverSocket = new ServerSocket(6013);
while (true) {
client = serverSocket.accept();
OutputStream outputStream = client.getOutputStream();
InputStream inputStream = client.getInputStream();
System.out.println("" + outputStream + "-" + inputStream);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
System.out
.println("Message recieved from client ::" + line);
}
PrintWriter printWriter = new PrintWriter(outputStream, true);
printWriter.println(new java.util.Date().toString());
client.close();
}
} catch (IOException exception) {
exception.printStackTrace();
System.err.println(exception);
}
}
}
客户:
public class DateClient {
public static void main(String[] args) throws UnknownHostException,
IOException, InterruptedException {
Socket sock = new Socket("127.0.0.1", 6013);
OutputStream outputStream = sock.getOutputStream();
InputStream inputStream = sock.getInputStream();
System.out.println("" + outputStream + "-" + inputStream);
PrintWriter printWriter = new PrintWriter(outputStream, true);
printWriter.println("Hi Server");
outputStream.close();
System.out.println(sock.isConnected());
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null) { // Exception
System.out.println(line);
}
}
}
在客户端中获取以下套接字已关闭的异常。能不能让我知道原因是什么。
Exception in thread "main" java.net.SocketException: Socket closed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(SocketInputStream.java:146)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:282)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:324)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:176)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:153)
at java.io.BufferedReader.readLine(BufferedReader.java:316)
at java.io.BufferedReader.readLine(BufferedReader.java:379)
at edu.iub.cs.httpserver.DateClient.main(DateClient.java:32)
答案 0 :(得分:10)
java.net.SocketException套接字已关闭 此异常意味着您关闭了套接字,然后继续尝试使用它。
os.close();
你在这里关闭它。关闭Socket的输入或输出流将关闭另一个流和Socket。
答案 1 :(得分:2)
java.net.SocketException
只有在您从服务器读取之前关闭OutputStream
(或)套接字时才会出现。
从您的代码中删除:
OutputStream.close();
然后尝试..