public class MyClient {
//客户端
public static void main(String[] args) throws UnknownHostException, IOException {
// TODO Auto-generated method stub
name(“E:/chenhuihong/newpic/vov.jpg”,“E:/chenhuihong/newpic/888.jpg”);
}
public static void name(String name ,String image) throws UnknownHostException, IOException {
File file = new File(name);
File file2 = new File(image);
Socket socket = new Socket(“localhost”,8888);
OutputStream outputStream=socket.getOutputStream();
InputStream inputStream=socket.getInputStream();
System.out.println(“开始接收”);
try (FileOutputStream fileOutputStream=new FileOutputStream(file);
FileInputStream fileInputStream = new FileInputStream(image)){
byte[] ch = new byte[100];
int a = -1;
while ((a=inputStream.read(ch)) !=-1) {
fileOutputStream.write(ch,0,a);
}
System.out.println(“客户端接收完成===”);
Socket socket =serverSocket.accept();//关闭输入
byte[] ch2 = new byte[120];
int b = -1;
while ((b=fileInputStream.read(ch2)) != -1) {
outputStream.write(ch2,0,b);
}
System.out.println("客户端传输完成---");
outputStream.flush();
outputStream.close();
inputStream.close();
fileOutputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
- 传输一张图片
*/
public class MyServer {
//服务器
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
name(“E:/chenhuihong/wu.jpg”,“E:/chenhuihong/w3c.jpg”);
}
public static void name(String name,String image) throws IOException {
File file = new File(name);
File file2 = new File(image);
Scanner se = new Scanner(System.in);
//创建服务器
ServerSocket serverSocket=new ServerSocket(8888);
System.out.println(“正在等待连接”);
//等带客户连接
Socket socket =serverSocket.accept();
//获取对应输出对象
OutputStream outputStream=socket.getOutputStream();
InputStream inputStream=socket.getInputStream();
try (FileInputStream fileInputStream=new FileInputStream(file);
FileOutputStream fileOutputStream = new FileOutputStream(file2)){
byte [] ch = new byte[100];
int a = -1;
while ((a=fileInputStream.read(ch)) != -1) {
outputStream.write(ch,0,a);
}
System.out.println(“服务器传输成功===”);
Socket socket =serverSocket.accept();//关闭输入
byte[] ch2 = new byte[150];
int b = -1;
while ((b = inputStream.read(ch2)) !=-1) {
fileOutputStream.write(ch2,0,b);
}
System.out.println("服务器接收成功---");
outputStream.flush();
outputStream.close();
inputStream.close();
fileInputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}