客户端:
package practice;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class Practice1 {
public static void main(String[] args) throws UnknownHostException,
IOException {
// 1.创建客户端socket
Socket s = new Socket(InetAddress.getLocalHost(), 8800);
// 2.获取输入流
FileInputStream fis = new FileInputStream("C:\\Users\\windows7\\Desktop\\249053975.jpg");
// 3.获取socket输出流,将图片数据发送给服务端。
OutputStream os = s.getOutputStream();
byte[]buf = new byte[1024];
int len = 0;
while((len = fis.read(buf))!=-1){
os.write(buf, 0, len);
}
//告诉服务端这边的数据发送完毕,让服务端停止
s.shutdownOutput();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String str =null;
str = br.readLine();
System.out.println(str);
fis.close();
s.close();
}
}
服务端
package practice;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class PracticeServer {
public static void main(String[] args) throws IOException {
ServerSocket ss= new ServerSocket(8800);
Socket s = ss.accept();
String ip = s.getInetAddress().getHostAddress();
InputStream is = s.getInputStream();
File dir =new File("c:\\pic");
if(!dir.exists()){
dir.mkdirs();
}
File file = new File(dir, ip+".bmp");
FileOutputStream fos = new FileOutputStream(file);
byte[]buf = new byte[1024];
int len = 0;
while(((len=is.read(buf))!=-1)){
fos.write(buf, 0, len);
}
OutputStream out = s.getOutputStream();
out.write("上传成功".getBytes());
fos.close();
ss.close();
}
}
服务端没事。客户端我基本按照老毕的视频写的,只有最后读取服务端回传信息时用了bufferedreader,视频中用的是inputstream
请问我这么写有哪里不对吗?总是报Exception in thread "main" java.net.SocketException: Connection reset异常
求大神讲解
|
|