java.net.SocketException: Connection reset 问题解决方法

java.net.SocketException: Connection reset 问题解决方法
客户端用长连接进行连接,也就是写个死循环,while ture;用
while((temp = inputStream.read(buffer)) != -1){
System.out.println(new String(buffer,0,temp));
}
会报java.net.SocketException: Connection reset 异常

----------》服务端


import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerDemo {

public static void main(String[] args) {
new ServerThread().start();
}
}

class ServerThread extends Thread{
public void run(){
//声明一个ServerSocket对象
ServerSocket serverSocket = null;
try {
//创建一个ServerSocket对象,并让这个Socket在4567端口监听
serverSocket = new ServerSocket(4568);
byte buffer [] = new byte[1024*4];
int temp = 0;
//从InputStream当中读取客户端所发送的数据
while(true){
//调用ServerSocket的accept()方法,接受客户端所发送的请求
Socket socket = serverSocket.accept();
//从Socket当中得到InputStream对象
InputStream inputStream = socket.getInputStream();
temp = inputStream.read(buffer);
System.out.println(new String(buffer,0,temp));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
/* public void run(){
try {
//创建一个DatagramSocket对象,并指定监听的端口号
DatagramSocket socket = new DatagramSocket(4567);
byte data [] = new byte[1024];
//创建一个空的DatagramPacket对象
DatagramPacket packet = new DatagramPacket(data,data.length);
//使用receive方法接收客户端所发送的数据
socket.receive(packet);
String result = new String(packet.getData(),packet.getOffset(),packet.getLength());
System.out.println("result--->" + result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
}


-----------》客户端

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.Socket;

public class TCPClient {
public static void main(String[] args) {
try {
//创建一个Socket对象,指定服务器端的IP地址和端口号
Socket socket = new Socket("192.168.1.103",4568);
//使用InputStream读取硬盘上的文件
InputStream inputStream = new FileInputStream("C://Documents and Settings/Administrator/桌面/临时备份/fileTest/1.txt");
//从Socket当中得到OutputStream
OutputStream outputStream = socket.getOutputStream();
byte buffer [] = new byte[4*1024];
int temp = 0 ;
//将InputStream当中的数据取出,并写入到OutputStream当中
while((temp = inputStream.read(buffer)) != -1){
outputStream.write(buffer, 0, temp);
}
outputStream.flush();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

你可能感兴趣的:(java,咱们有缘吗)