网络编程_TCP协议上传图片并给出反馈

来源:互联网 发布:淘宝地址怎么删除不了 编辑:程序博客网 时间:2024/05/21 06:44
package cn.itcast_13;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;/* * TCP协议上传图片并给出反馈 */public class UploadServer {public static void main(String[] args) throws IOException {// 创建服务器Socket对象ServerSocket ss = new ServerSocket(45678);// 监听客户端链接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();}}


package cn.itcast_13;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.net.Socket;/* * TCP协议上传图片并给出反馈 */public class UploadClient {public static void main(String[] args) throws IOException {// 创建客户端Socket对象Socket s = new Socket("192.168.31.165", 45678);// 封装图片文件BufferedInputStream bis = new BufferedInputStream(new FileInputStream("林青霞.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 client = new String(bys2, 0, len2);System.out.println(client);// 释放资源bis.close();s.close();}}


0 0
原创粉丝点击