Java基础知识强化之网络编程笔记13:TCP之TCP协议上传图片并给出反馈
2015-10-12 19:24
981 查看
1. TCP协议上传图片并给出反馈:
(1)客户端:
(2)服务端:
(1)客户端:
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; public class UploadClient { public static void main(String[] args) throws IOException { // 创建客户端Socket对象 Socket s = new Socket("192.168.12.92", 19191); // 封装图片文件 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(); } }
(2)服务端:
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; public class UploadServer { public static void main(String[] args) throws IOException { // 创建服务器Socket对象 ServerSocket ss = new ServerSocket(19191); // 监听客户端连接 Socket s = ss.accept(); // 封装通道内流 BufferedInputStream bis = new BufferedInputStream(s.getInputStream()); // 封装图片文件 BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream("mn.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(); } }
相关文章推荐
- HTTP协议
- Java基础知识强化之网络编程笔记12:TCP之TCP协议上传文本文件并给出反馈
- android:安卓中5中网络请求库之Vellory OkHttp Retrofit
- 计算机网络
- Java基础知识强化之网络编程笔记11:TCP之TCP协议上传文本文件
- Java基础知识强化之网络编程笔记10:TCP之客户端读取文本文件服务器控制台输出
- “大师兄”社区(http://www.daxixiong.com/)欢迎你!!!
- 客户端通过http访问服务器端乱码问题的解决方案
- 网络编程 笔记(三) 套接字类型 协议设置
- iOS通过HTTP POST上传文件
- CPU亲缘性及网卡中断绑定
- 从源码安装apache httpd,并加载对php的支持
- ios测试基础一:mac下HTTP与HTTPS抓包
- POJ 1149 PIGS
- android中URLConnection和HttpURLConnection
- IOS网络编程简单介绍
- http\网络\
- HTTP协议初识
- Android中基于Http请求获取数据基础
- HTTP (http://) resource load since it is insecure.