java.net.socketexception: connection reset
是在服务器端出现的错误,还是在客户端出现的错误?
出现该错误应该是连接异常关闭造成的。
由于你的代码不全,如果没有看错的话下面的错误
at com.beiju.main(beiju.java:38)
应是
if (input.read(serverbyte) == 0)
代码抛出的错误
应该是你读字节流时阻塞了,最后超时导致
java.net.socketexception: connection reset
由于代码不全,只能简单的改写一下,调整了一下代码结构,解决读取流字节为空的问题。
但是,由于字节流超过1024个字节,导致read阻塞的问题还没有改。这需要使用 input.available() 方法。
以下是重新改写的代码,已经测试通过,运行即可,有问题请给我留言。
public static void main(string[] args) throws unknownhostexception,
ioexception {
socket socket = null;
outputstream output = null;
inputstream input = null;
byte clientbyte[] = new byte[2]; // 发送给服务端的字节数组
byte serverbyte[] = new byte[1024];// 接收给服务端的字节数组
clientbyte[0] = (byte) 0xc1; // 给数组赋值
clientbyte[1] = (byte) 0x01; // 给数组赋值
try {
socket = new socket("127.0.0.1", 10000); // 连接服务端
output = socket.getoutputstream(); // 获得socket 连接的输出流
input = socket.getinputstream(); // 获得socket 连接的输入流,需要提前构造,否则无法接收数据
output.write(clientbyte); // 把clientbyte写入输出流
// byte bb[] = "aaaa\n".getbytes();
// output.write(bb); // 把clientbyte写入输出流
output.flush(); // 刷新此输出流并强制写出所有缓冲的输出字节。
// 读取输入流返回为0,提示没收到字节!
//因为使用了缓存数组1024,所以一次性读满1024。否则将使用while进行循环读取,直到input.read(serverbyte) == -1
int len = input.read(serverbyte);
if (len > 0) {//读取到字节
system.out.println("读取到字节。! " + len);
} else if (len == 0) {//没有读取到字节
system.out.println("没有取到字节。!");
// 读取输入流返回为-1,提示没有可用的字节 !
} else if (len == -1) {//读取结束
system.out.println("读取结束");
}
//循环显示读取到的数据
for(int i = 0 ; i < serverbyte.length ; i++){
system.out.print(serverbyte[i]);
}
system.out.println("");
} catch (exception e) {
e.printstacktrace();
} finally{
if(input != null){
try{
input.close();
}catch(exception e) {}
}
if(output != null){
try{
output.close();
}catch(exception e) {}
}
if(socket != null){
try{
socket.close();
}catch(exception e) {}
}
}
}