我正在学习Java中的Socket编程。我得到了java.net.SocketException: Connection reset
。
客户端代码
package com.socket;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class ClientSock {
public static void main(String[] args) throws Exception {
Socket skt = new Socket("localhost", 8888);
String str = "Hello Server";
OutputStreamWriter osw = new OutputStreamWriter(skt.getOutputStream());
PrintWriter out = new PrintWriter(osw);
osw.write(str);
osw.flush();
}
}
//Server Side Code:
package com.socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerSock {
public static void main(String[] args) throws Exception {
System.out.println("Server is Started");
ServerSocket ss = new ServerSocket(8888);
Socket s = ss.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String str = br.readLine();
System.out.println("Client Says : " + str);
}
}
这是运行客户端代码后我的控制台,我正在重置异常连接,我做错了吗?
Server is Started
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at com.socket.ServerSock.main(ServerSock.java:19)
答案 0 :(得分:2)
"线程中的异常" main" java.net.SocketException:连接重置"当对手被强行终止而没有调用close()时会发生错误。
将此行添加到ClientSock
skt.close();
我也向ServerSock推荐这个。
ss.close();
java.io.Closeable实现对象必须调用close()。
答案 1 :(得分:0)
你忘了" \ n"在您的" Hello Server"。
读者无法获得整行并抛出此异常。