我收到一个 java.net.SocketException: 连接重置错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20340806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
I am getting a java.net.SocketException: Connection reset error
提问by gallly
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Set;
public class Server {
// ArrayList<PrintWriter> writers; // hold a list of current connections
Set<Socket> sockets = new HashSet<Socket>();
private ServerSocket serverSocket;
private Socket sock;
private static SimpleDateFormat date = new SimpleDateFormat(
"dd/mm/yyyy hh:mm:ss");
private static Calendar cal = Calendar.getInstance();
public static void main(String[] args) {
new Server().go();
}
public void go() {
try {
// setup port listener
// add connections to arraylist
// setup in and out streams
System.out.println("waiting connetion");
serverSocket = new ServerSocket(8999);
// writers = new ArrayList<PrintWriter>();
while (true) {
sock = serverSocket.accept();
sockets.add(sock);
// PrintWriter writer = new PrintWriter(
// sock.getOutputStream());
// writers.add(writer);
Thread t = new Thread(new ClientHandler(sock));
t.start();
System.out.println("connected");
}
} catch (IOException ex) {
ex.printStackTrace();
System.out.println("fail setup network");
} finally {
System.out.println("finally");
}
}
class ClientHandler implements Runnable {
private BufferedReader in;
public ClientHandler(Socket sock) {
// setup a client connection
try {
in = new BufferedReader(new InputStreamReader(
sock.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
System.out.println("fail classhandler");
}
}
@Override
public void run() {
// receive and relay messages back to clients
String message;
try {
while ((message = in.readLine()) != null) {
shout(message);
System.out.println("client says : "
+ date.format(cal.getTime()) + message);
}
} catch (IOException ex) {
try {
System.out.println("closing");
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
sockets.remove(sock);
System.out.println(sockets);
ex.printStackTrace();
System.out.println("fail read message");
}
}
public synchronized void shout(String message) {
// send message to all clients
// for (PrintWriter writer : writers) {
// writer.println(date.format(cal.getTime()) + " " + message
// + "\n");
// writer.flush();
// }
for (Socket sock : sockets) {
try {
PrintWriter writer = new PrintWriter(sock.getOutputStream());
writer.println(date.format(cal.getTime()) + " " + message
+ "\n");
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
=======================================================
================================================== ======
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Client {
private JTextArea tArea;
private BufferedReader in;
private Socket sock;
private PrintWriter out;
public static void main(String[] args) {
new Client().go();
}
public void go() {
JFrame frame = new JFrame("Chat Client");
final JTextField tField = new JTextField(25);
tArea = new JTextArea(30, 20);
JButton button = new JButton("send");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
sendMessage(tField.getText());
tField.setText("");
}
});
frame.setSize(300, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(tArea, BorderLayout.NORTH);
frame.add(tField, BorderLayout.CENTER);
frame.add(button, BorderLayout.EAST);
frame.pack();
setupNetwork();
Thread t = new Thread(new IncomingReader());
t.start();
}
public void setupNetwork() {
try {
sock = new Socket("localhost", 8999);
in = new BufferedReader(
new InputStreamReader(sock.getInputStream()));
out = new PrintWriter(sock.getOutputStream());
} catch (IOException ex) {
ex.printStackTrace();
System.out.println("fail networking");
}
}
class IncomingReader implements Runnable {
public void run() {
//receive messages from server
try {
String message = null;
while ((message = in.readLine()) != null) {
tArea.append(message + "\n");
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("fail incoming reader");
}
}
}
public void sendMessage(String message) {
try {
out.println(message);
out.flush();
} catch (Exception e) {
e.printStackTrace();
System.out.println("fail send message");
}
}
}
when I close a client I get this error and I tried somethings with closing my connections but ultimately I am not sure how to get rid of this error:
当我关闭客户端时,我收到此错误,并尝试关闭连接,但最终我不确定如何摆脱此错误:
fail read message
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 Server$ClassHandler.run(Server.java:63)
at java.lang.Thread.run(Unknown Source)
I know its because I am closing a connection but it keeps throwing this error and its annoying even though it doesn't break my server.
我知道这是因为我正在关闭一个连接,但它不断抛出这个错误并且很烦人,即使它没有破坏我的服务器。
回答by dimoniy
That's because you should properly close the socket when you're done with it on the client. I'm not a SWING guru, but looks like WindowListeneris what you need. Just close the connection when main window is closed.
那是因为在客户端上完成套接字后,您应该正确关闭套接字。我不是 SWING 大师,但看起来WindowListener正是您所需要的。只需在主窗口关闭时关闭连接。
EDIT: When you close TCP socket, there is a little bit of job need to be done: http://en.wikipedia.org/wiki/Transmission_Control_Protocol#Connection_termination. When you close the program this is not going to happen. OS will close the connection for you and will free all of the associated resources, but server will not be notified about client closing the connection.
编辑:当您关闭 TCP 套接字时,需要完成一些工作:http: //en.wikipedia.org/wiki/Transmission_Control_Protocol#Connection_termination。当您关闭程序时,这不会发生。操作系统将为您关闭连接并释放所有相关资源,但服务器不会收到有关客户端关闭连接的通知。
EDIT 2: Demonstration Server:
编辑 2:演示服务器:
public class Server {
public static void main(String args[]) {
try {
System.out.println("waiting connetion");
ServerSocket serverSocket = new ServerSocket(8999);
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Connected");
Reader reader = new InputStreamReader(
clientSocket.getInputStream());
reader.read(); // wait for input
System.out.println("No exception");
}
} catch (IOException ex) {
System.out.println("Exception");
ex.printStackTrace();
}
}
}
Client:
客户:
public class Client {
public static void main(String args[]) throws Exception {
Socket sock = new Socket("localhost", 8999);
System.out.println("Press 1 to close gracefully, any other nuber otherwise");
Scanner sc = new Scanner(System.in);
if (sc.nextInt() ==1 ) {
sock.close();
} else {
//do nothing
}
}
}
回答by user207421
The usual cause of this is that you have written to a connection that has already been closed by the other end. In other words, an application protocol error.
造成这种情况的通常原因是您已写入已被另一端关闭的连接。换句话说,应用程序协议错误。
The specific problem here is that when you get null
from readLine()
in the server, you should close that socket and remove the corresponding Writer
from the array of writers to shout at.
这里的具体问题是,当您null
从readLine()
服务器中获取时,您应该关闭该套接字并Writer
从要大喊大叫的作家数组中删除相应的套接字。
回答by Sagar Bhosale
To tell the java code that all HTTP request should be routed through the proxy use the below snippet:
要告诉 Java 代码所有 HTTP 请求都应通过代理路由,请使用以下代码段:
System.setProperty("http.proxyHost", "proxyHost");
System.setProperty("http.proxyPort", "proxyPort");
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication("USERNAME","PASSWORD".toCharArray()));
}
};
Authenticator.setDefault(authenticator);
The System.setProperty sets the proxy host and port. The Authenticator should be your corporate username and password. This should work now.
System.setProperty 设置代理主机和端口。身份验证器应该是您的公司用户名和密码。这现在应该可以工作了。
回答by sonuk9178
put socketname.close()
method in your client...the problem is that the client gets finished up before the server could read streams from it...
putsocketname.close()
方法在你的客户端......问题是客户端在服务器可以从中读取流之前完成......