我想寫一個tcp客戶端和服務器程序。服務器的工作就好了,它通常打開插座,但是當我運行客戶端程序,我得到以下錯誤:爲什麼我會得到「java.net.SocketExcpecption:連接重置」?
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at server.Client.main(Client.java:22)
誰能告訴我怎麼解決?在此先感謝
這裏是我的客戶端代碼
public class Client {
private final static String serverIP = "192.168.56.1";
private final static int serverPort = 50000;
private final static String fileOutput ="D:\\Julian\\Kancolle.7z";
public static void main(String args[]) throws UnknownHostException, IOException {
Socket sock = new Socket(serverIP, serverPort);
byte[] byte_arr = new byte[1024];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream(fileOutput);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(byte_arr, 0, byte_arr.length);
bos.write(byte_arr, 0, bytesRead);
bos.close();
sock.close();
}
}
和服務器代碼
public class Server implements Runnable {
private final static int serverPort = 50000; // reserves port
private final static String fileInput = "D:\\Julian\\Kancolle"; // destination
public static void main(String args[]) throws IOException{
int bytesRead; // buffer variable
ServerSocket servsock = new ServerSocket(serverPort);
File myFile = new File(fileInput);
while (true) {
Socket sock = servsock.accept();
InputStream in = sock.getInputStream();
OutputStream output = new FileOutputStream(myFile);
byte[] buffer = new byte[1024]; // buffer
while((bytesRead = in.read(buffer)) != -1)
{
output.write(buffer, 0, bytesRead);;
}
output.close();
servsock.close();
}
}
public static void start(){
Server upd = new Server();
Thread tupd = new Thread(upd);
tupd.start();
}
@Override
public void run() {
}
}
此代碼不會產生此異常,除非您終止了服務器進程。 – EJP