欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

TCP之上传图片并给出反馈

程序员文章站 2022-04-15 18:38:51
SeverDomepackage cn.itcast_05;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;/* *...

SeverDome

package cn.itcast_05;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/*
 * 上传图片并给出反馈
 */
public class SeverDome {

	public static void main(String[] args) throws IOException {
		
		// 创建服务器对象
		ServerSocket ss = new ServerSocket(12345);
		
		//监听客户端连接
		Socket s = ss.accept();
		
		//封装通道数据
		BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
		
		
		//封装图片文件
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("a.jpg"));
			
		byte[] bys = new byte[1024];
		int len = 0;
		while((len = bis.read(bys)) != -1) {
			bos.write(bys,0, len);
			bos.flush();
		}
		//给一个反馈
		OutputStream os = s.getOutputStream();
		os.write("图片上传成功".getBytes());
		
		//释放资源
		bos.close();
		s.close();
	}
}

ClientDome

package cn.itcast_05;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

public class ClientDome {

	public static void main(String[] args) throws IOException {
		
		// 创建客户端对象
		Socket s = new Socket("10.212.31.21",12345);
		
		//封装图片
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream("ling.jpg"));
		
		//封装发送到通道流
		BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
		
		byte[] bys = new byte[1024];
		int len = 0;
		while((len = bis.read(bys)) != -1) {
			bos.write(bys,0,len);
			bos.flush();
		}
		
		s.shutdownOutput();
		
		//接受反馈
		InputStream is = s.getInputStream();
		byte[] bys2 = new byte[1024];
		int len2= is.read(bys2);
		String Cilent = new String (bys2, 0, len2);
		System.out.println(Cilent);
		
		//释放资源
		bis.close();
		s.close();
	}
}

本文地址:https://blog.csdn.net/kaszxc/article/details/109264905