网络传输一张图片,客户端和服务器之间的图片交换

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();
	}
	

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值