下面是小弟客户端发送接收数据对的代码,总是在读取服务器返回的数据报错“connection reset”:
public class Client {
public static String DoClient(String host, int port, String data) {
Socket soc = null;
OutputStream out = null;
InputStream is = null;
BufferedReader br = null;
String info = null;
try {
soc = new Socket(host, port);
out = soc.getOutputStream();
String length = String.format("%04d", data.length());
out.write(length.getBytes());
out.write(data.getBytes());
out.flush();
soc.shutdownOutput();
System.out.println("发送的数据长度为" + length);
is = soc.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
while ((info = br.readLine()) != null) {
System.out.println("我是客户端,服务器说:" + info);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
is.close();
out.close();
if (soc != null) {
soc.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return info;
}
}
之前没写过这种方式的通讯模式,跪求大神给个详细的解决方案!!!
引起这个异常的原因有两个:
一、客户端和服务器端如果一端的Socket被关闭,另一端仍发送数据,发送的第一个数据包引发该异常;
二、客户端和服务器端一端退出,但退出时并未关闭该连接,另一端如果在从连接中读数据则抛出该异常。
哥!我又一次也是写这破玩意!最好敲个断点或者Syso自己慢慢排吧!我第一写为了装个B想用WEB当窗口写了10天服务端死活不显示客户端的信息,其余都好使
首先确定一下进没进你的服务端!而且我看一下你这应该是服务端,可你的端口号和IP地址在哪里?如果是客户端你的端口在哪?
服务端的代码可以贴出来看看 或者私信我
java.net.SocketException: Connection reset
引起这个异常的原因有两个:
一、客户端和服务器端如果一端的Socket被关闭,另一端仍发送数据,发送的第一个数据包引发该异常;
二、客户端和服务器端一端退出,但退出时并未关闭该连接,另一端如果在从连接中读数据则抛出该异常。
简单来说就是在连接断开后的读和写操作引起的。
你检查一下你的连接。
这是我在网上看到的,觉得挺对的,还有就是你数据包也不能太大,最好是将网络的节点流包装成处理流再去传输要好一点。
你看看这篇博客,https://my.oschina.net/xionghui/blog/508758
你这个错误,根据错误信息‘Connection reset’ 可以大概猜测到应该是服务器端的原因造成的服务器端强制关闭了和客户端的链接。具体原因不太清楚,需要看你服务端的代码才行。 我猜测的原因如下:
1、服务端报错了,且未处理,强制关闭了连接。
2、服务端和客户端通信使用的是短连接,导致服务端关闭了连接。
还是贴下代码嘛!
因为你在服务端没返回数据之前,就关闭了长连接
public static String DoClient(String host, int port, String data) {
Socket soc = null;
OutputStream out = null;
InputStream is = null;
BufferedReader br = null;
String info = null;
try {
// 此处创建socket
soc = new Socket(host, port);
out = soc.getOutputStream();
String length = String.format("%04d", data.length());
// 你给服务端写入了数据
out.write(length.getBytes());
out.write(data.getBytes());
out.flush();
// 然后你就把流关闭了,所以后面的读操作就不能执行了
// soc.shutdownOutput();
System.out.println("发送的数据长度为" + length);
is = soc.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
while ((info = br.readLine()) != null) {
System.out.println("我是客户端,服务器说:" + info);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
is.close();
out.close();
if (soc != null) {
soc.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return info;
}
现在已经好了 是由于使用了bufferReader.readline()方法导致被挂起,一直读取不到相关的返回信息,用字节流接收已经ok!
java.net.SocketException: Connection reset
引起这个异常的原因有两个:
一、客户端和服务器端如果一端的Socket被关闭,另一端仍发送数据,发送的第一个数据包引发该异常;
二、客户端和服务器端一端退出,但退出时并未关闭该连接,另一端如果在从连接中读数据则抛出该异常。
简单来说就是在连接断开后的读和写操作引起的。
你检查一下你的连接。