http stream
- StringBuilder sb = new StringBuilder();
- sb.append("HTTP/1.1 200 OK\r\n");
- sb.append("Content-Type: text/plain\r\n");
- sb.append("Transfer-Encoding: chunked\r\n\r\n");
- sb.append("25\r\n");
- sb.append("This is the data in the first chunk\r\n"); // 37 bytes
- sb.append("\r\n1A\r\n");
- sb.append("and this is the second one"); // 26 bytes
- sb.append("\r\n0\r\n\r\n");
十六进制包长+\r\n+报文包+\r\n 为一个传输单元
0+\r\n+\r\n 当遇到这种空传输单元时结束
下面是客户端例子
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.net.InetSocketAddress;
- import java.net.Socket;
- import java.nio.ByteBuffer;
- import java.nio.channels.SocketChannel;
- import java.util.concurrent.Callable;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.FutureTask;
- public class Client {
- public boolean isAsync=false;
- /**
- * 建立socket
- * @param ip
- * @param port
- * @return
- * @throws IOException
- * @throws NumberFormatException
- * @throws PachiraAsrSocketCreateException
- */
- protected SocketChannel createSocketChannel(String ip,String port) throws NumberFormatException, IOException {
- SocketChannel socketChannel=null;
- if(isAsync){
- socketChannel = SocketChannel.open();
- socketChannel.configureBlocking(false);
- //向服务端发起连接
- if (!socketChannel.connect(new InetSocketAddress(ip, Integer.parseInt(port)))){
- //不断地轮询连接状态,直到完成连接
- while (!socketChannel.finishConnect()){
- //在等待连接的时间里,可以执行其他任务,以充分发挥非阻塞IO的异步特性
- //这里为了演示该方法的使用,只是一直打印"."
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- }
- // SrvLogger.debug(getClass(), "");
- }
- }
- }else{
- socketChannel = SocketChannel.open();
- socketChannel.connect(new InetSocketAddress(ip, Integer.parseInt(port)));
- }
- return socketChannel;
- }
- /**
- * 关闭socket
- * @param socketChannel
- * @param uuid
- * @throws IOException
- */
- protected void closeSocketChannel(SocketChannel socketChannel) throws IOException{
- if(socketChannel!=null){
- socketChannel.close();
- }
- }
- /**
- * 传输数据
- * @param socket
- * @param in
- * @param uuid
- * @param audioType
- * @throws IOException
- */
- protected boolean sendStringData(final SocketChannel socketChannel ,final String str) throws IOException{
- ByteBuffer buffer=ByteBuffer.wrap(str.getBytes(), 0, str.length());
- int size=0;
- int wl=0;
- System.out.println("buf.limit="+buffer.limit());
- wl=socketChannel.write(buffer);
- while (buffer.hasRemaining()) {
- if (wl < 0){
- System.out.println("sendData len is -1;size="+size);
- break;
- }
- if (wl == 0) {
- System.out.println("sendData len is 0 ;size="+size);
- }
- size+=wl;
- }
- buffer.flip();
- return true;
- }
- /**
- * 传输数据
- * @param socket
- * @param in
- * @param uuid
- * @param audioType
- */
- protected boolean sendData(final SocketChannel socketChannel ,final InputStream is){
- FutureTask<Integer> task = new FutureTask<Integer>(new Callable<Integer>(){
- public Integer call() {
- System.out.println("sendData start...;");
- byte[] buf = new byte[8096];
- int totalSize=0;
- int sendTotalSize=0;
- try {
- int read = is.read(buf, 0, buf.length);
- while (read > 0) {
- totalSize+=read;
- ByteBuffer buffer=ByteBuffer.wrap(buf, 0, read);
- int size=0;
- int wl=0;
- wl=socketChannel.write(buffer);
- while (buffer.hasRemaining()) {
- if (wl < 0){
- System.out.println("sendData len is -1;size="+size);
- break;
- }
- if (wl == 0) {
- System.out.println("sendData len is 0 ;size="+size);
- }
- size+=wl;
- }
- buffer.flip();
- sendTotalSize+=read;
- read = is.read(buf, 0, buf.length);
- }
- sendStringData(socketChannel, "------------V2ymHFg03ehbqgZCaKO6jy--");
- System.out.println("sendData end,sendTotalSize="+sendTotalSize+";totalSize="+totalSize);
- }catch (Exception e) {
- e.printStackTrace();
- }finally{
- }
- return new Integer(8);
- }
- });
- ExecutorService sendDataPool=Executors.newCachedThreadPool();
- sendDataPool.execute(task);
- return true;
- }
- /**
- * 传输数据
- * 十六进制包长+\r\n+报文包+\r\n 为一个传输单元
- 0+\r\n+\r\n 当遇到这种空传输单元时结束
- * @param socket
- * @param in
- * @param uuid
- * @param audioType
- */
- protected boolean sendDataChunk(final SocketChannel socketChannel ,final InputStream is){
- FutureTask<Integer> task = new FutureTask<Integer>(new Callable<Integer>(){
- public Integer call() throws IOException {
- System.out.println("sendData start...;");
- sendStringData(socketChannel, "\r\n");
- String parameter="------------V2ymHFg03ehbqgZCaKO6jy\r\nContent-Disposition: form-data;name=\"chon.wav\";opcode=\"transcribe_audio\";sessionid=\"\";filename=\"chon.wav\";type=\"23\";\r\n\r\n";
- sendStringData(socketChannel, Integer.toHexString(parameter.length())+"\r\n");
- sendStringData(socketChannel, parameter+"\r\n");
- // sendStringData(socketChannel, Integer.toHexString("1234".length())+"\r\n1234\r\n");
- // sendStringData(socketChannel, Integer.toHexString("1234".length())+"\r\n1234\r\n");
- // sendStringData(socketChannel, Integer.toHexString("1234".length())+"\r\n1234\r\n");
- // sendStringData(socketChannel, Integer.toHexString("1234".length())+"\r\n1234\r\n");
- // sendStringData(socketChannel, Integer.toHexString("------------V2ymHFg03ehbqgZCaKO6jy".length())+"\r\n");
- // sendStringData(socketChannel, "------------V2ymHFg03ehbqgZCaKO6jy\r\n");
- // String parameter="Content-Disposition: form-data;name=\"chon.wav\";opcode=\"transcribe_audio\";sessionid=\"\";filename=\"chon.wav\";type=\"23\";";
- // sendStringData(socketChannel, Integer.toHexString(parameter.length())+"\r\n");
- // sendStringData(socketChannel, parameter+"\r\n");
- byte[] buf = new byte[8096];
- int totalSize=0;
- int sendTotalSize=0;
- try {
- int read = is.read(buf, 0, buf.length);
- while (read > 0) {
- totalSize+=read;
- ByteBuffer buffer=ByteBuffer.wrap(buf, 0, read);
- String hex= Integer.toHexString(read);
- System.out.println("read="+read+";hex="+hex);
- sendStringData(socketChannel,hex+"\r\n");
- int size=0;
- int wl=0;
- // System.out.println("send..");
- wl=socketChannel.write(buffer);
- // System.out.println("send...");
- while (buffer.hasRemaining()) {
- if (wl < 0){
- System.out.println("sendData len is -1;size="+size);
- break;
- }
- if (wl == 0) {
- System.out.println("sendData len is 0 ;size="+size);
- }
- size+=wl;
- }
- sendStringData(socketChannel, "\r\n");
- buffer.flip();
- sendTotalSize+=read;
- read = is.read(buf, 0, buf.length);
- Thread.sleep(50);
- }
- sendStringData(socketChannel, Integer.toHexString("------------V2ynHFg03ehbqgZCaKO6jy--".length())+"\r\n");
- sendStringData(socketChannel, "------------V2ymHFg03ehbqgZCaKO6jy--");
- sendStringData(socketChannel, "\r\n");
- sendStringData(socketChannel, "0\r\n\r\n");
- System.out.println("sendData end,sendTotalSize="+sendTotalSize+";totalSize="+totalSize);
- }catch (Exception e) {
- e.printStackTrace();
- }finally{
- }
- return new Integer(8);
- }
- });
- ExecutorService sendDataPool=Executors.newCachedThreadPool();
- sendDataPool.execute(task);
- return true;
- }
- /**
- * 读取
- * @param inputStream
- * @param buf
- * @return
- * @throws IOException
- */
- protected boolean readData(SocketChannel socketChannel, ByteBuffer buf) {
- boolean ret = true;
- long count=0;
- try {
- count = socketChannel.read(buf);
- // if(this.isAsync){
- while(count<buf.limit()){
- if(count==-1){
- System.out.println("readData count is -1");
- return false;
- }
- count += socketChannel.read(buf);
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- return false;
- }
- }
- // System.out.println("buffer.position()="+buf.position()+";buffer.limit()="+buf.limit());
- // System.out.println("count="+count);
- // }
- if(count>0){
- buf.flip();
- }
- } catch (Exception e) {
- ret=false;
- }finally{
- System.out.println("readData count="+count+";bufLen="+buf.limit());
- }
- return ret;
- }
- /**
- * 读取
- * @param inputStream
- * @param buf
- * @return
- * @throws IOException
- */
- protected boolean readDataBySocket(SocketChannel socketChannel) throws IOException {
- Socket socket=socketChannel.socket();
- InputStream in=socket.getInputStream();
- byte[] buf1=new byte[7];
- while(this.read(in, buf1)){
- System.out.println("result"+new String(buf1));
- }
- return false;
- }
- protected boolean read(InputStream inputStream, byte[] buf)
- throws IOException {
- boolean ret = true;
- int totalSize = buf.length;
- int read = inputStream.read(buf, 0, buf.length);
- while (read < totalSize) {
- read += inputStream.read(buf, read, (totalSize - read));
- }
- return ret;
- }
- public void nonstream() throws IOException{
- String ip="127.0.0.1";
- String port="8080";
- File file=new File("I:/1/pase/90s_9.wav");
- FileInputStream fis=new FileInputStream(file);
- SocketChannel socketChannel=createSocketChannel(ip, port);
- String parameter="------------V2ynHFg03ehbqgZCaKO6jy\r\nContent-Disposition: form-data;name=\"chon.wav\";opcode=\"transcribe_audio\";sessionid=\"\";filename=\"chon.wav\";type=\"0\";";
- sendStringData(socketChannel, "POST /project/uploader HTTP/1.1\r\n");
- sendStringData(socketChannel, "Accept: */*\r\n");
- sendStringData(socketChannel, "User-Agent: Mozilla/4.0\r\n");
- sendStringData(socketChannel, "Content-Length: "+(file.length()+parameter.length())+"\r\n");
- sendStringData(socketChannel, "Accept-Language: en-us\r\n");
- sendStringData(socketChannel, "Accept-Encoding: gzip, deflate\r\n");
- sendStringData(socketChannel, "Host: 127.0.0.1\r\n");
- sendStringData(socketChannel, "Content-Type: multipart/form-data;boundary=----------V2ymHFg03ehbqgZCaKO6jy\r\n");
- sendStringData(socketChannel, "\r\n");
- sendStringData(socketChannel, parameter+"\r\n");
- sendStringData(socketChannel, "\r\n");
- //send file1449930
- sendData(socketChannel, fis);
- // client.sendStringData(socketChannel, "------------V2ymHFg03ehbqgZCaKO6jy--");
- ByteBuffer bb=ByteBuffer.allocate(2000);
- readData(socketChannel, bb);
- byte[] b=new byte[bb.limit()];
- bb.get(b, 0, bb.limit()-1);
- System.out.println(new String(b));
- }
- public static void main(String[] args) throws NumberFormatException, IOException {
- String ip="localhost";
- String port="8080";
- Client client=new Client();
- // File file=new File("I:/1/a.txt");
- File file=new File("I:/1/pase/90s_9.wav");
- FileInputStream fis=new FileInputStream(file);
- SocketChannel socketChannel=client.createSocketChannel(ip, port);
- client.sendStringData(socketChannel, "POST /project/uploader HTTP/1.1\r\n");
- client.sendStringData(socketChannel, "Accept: */*\r\n");
- client.sendStringData(socketChannel, "User-Agent: Mozilla/4.0\r\n");
- // client.sendStringData(socketChannel, "Content-Length: "+(file.length()+parameter.length())+"\r\n");
- client.sendStringData(socketChannel, "Transfer-Encoding: chunked\r\n");
- client.sendStringData(socketChannel, "Accept-Language: en-us\r\n");
- client.sendStringData(socketChannel, "Accept-Encoding: gzip, deflate\r\n");
- client.sendStringData(socketChannel, "Host: 127.0.0.1\r\n");
- client.sendStringData(socketChannel, "Content-Type: multipart/form-data;boundary=----------V2ynHFg03ehbqgZCaKO6jy\r\n");
- //send file1449930
- client.sendDataChunk(socketChannel, fis);
- while(true){
- System.out.println("read start....");
- ByteBuffer bb=ByteBuffer.allocate(200);
- boolean flag=client.readData(socketChannel, bb);
- byte[] b=new byte[bb.limit()];
- bb.get(b, 0, bb.limit()-1);
- System.out.println(new String(b,"UTF-8"));
- if(!flag){
- System.out.println("socket close....");
- client.closeSocketChannel(socketChannel);
- break;
- }
- }
- System.out.println("read data end....");
- System.exit(0);
- }
- }
http stream的更多相关文章
- SQL Server-聚焦查询计划Stream Aggregate VS Hash Match Aggregate(二十)
前言 之前系列中在查询计划中一直出现Stream Aggregate,当时也只是做了基本了解,对于查询计划中出现的操作,我们都需要去详细研究下,只有这样才能对查询计划执行的每一步操作都了如指掌,所以才 ...
- Node.js:理解stream
Stream在node.js中是一个抽象的接口,基于EventEmitter,也是一种Buffer的高级封装,用来处理流数据.流模块便是提供各种API让我们可以很简单的使用Stream. 流分为四种类 ...
- node中的Stream-Readable和Writeable解读
在node中,只要涉及到文件IO的场景一般都会涉及到一个类-Stream.Stream是对IO设备的抽象表示,其在JAVA中也有涉及,主要体现在四个类-InputStream.Reader.Outpu ...
- nodejs中流(stream)的理解
nodejs的fs模块并没有提供一个copy的方法,但我们可以很容易的实现一个,比如: var source = fs.readFileSync('/path/to/source', {encodin ...
- Node学习笔记(一):stream流操作
NodeJs中谈及较多的可能就是Stream模块了,先写一个简单的ajax回调 $.post("index.php",{data:'aaa',order:'ccc'},functi ...
- Stream
Stream的好处 1.Stream AP的引入弥补了JAVA函数式编程的缺陷.2.Stream相比集合类占用内存更小:集合类里的元素是存储在内存里的,Stream里的元素是在访问的时候才被计算出来. ...
- Stream流
在Node中,存在各式各样不同的数据流,Stream(流)是一个由不同对象实现的抽象接口.例如请求HTTP服务器的request是一个 流,类似于stdout(标准输出):包括文件系统.HTTP 请求 ...
- [LeetCode] Data Stream as Disjoint Intervals 分离区间的数据流
Given a data stream input of non-negative integers a1, a2, ..., an, ..., summarize the numbers seen ...
- [LeetCode] Moving Average from Data Stream 从数据流中移动平均值
Given a stream of integers and a window size, calculate the moving average of all integers in the sl ...
- [LeetCode] Find Median from Data Stream 找出数据流的中位数
Median is the middle value in an ordered integer list. If the size of the list is even, there is no ...
随机推荐
- 你了解大O符号(big-O notation)么?你能给出不同数据结构的例子么?
大O符号表示当数据结构的元素增加的时候,算法规模或者性能在最坏场景下有多好. 大O符号也可以用来描述其他行为,比如说内存消耗.因为集合实际上就是一种数据结构,我们一般用大O符号基于时间.性能.内存消耗 ...
- keil的可烧写hex文件生成
右键Target1 Options Target for ‘Target1’ ...->Output->Create Executable:->Create HEX File Bui ...
- mail语法
在Linux系统下mail命令的用法 在Linux系统下mail命令的测试 1. 最简单的一个例子: mail -s test admin@aispider.com 这条命令的结果是发一封标题为tes ...
- [转]Haproxy原理(1)
本文出处:https://www.cnblogs.com/skyflask/p/6970151.html 目录 一.四层和七层负载均衡的区别二.HAProxy与LVS的异同三.快速安装HAProxy集 ...
- ckeditor_学习(1) 基本使用
ckeditor 是一款强大的web编辑器.工作需要用到记录学习和使用过程,版本是ckeditor4. 1.下载ckeditor的安装包,建议下载标准版的. j将ckeditor.js 引入页面,调用 ...
- Spring history&Design Philosophy 简单介绍~
SPRING框架的介绍和历史 Spring Framework是一个开源Java应用程序框架,最初是基于依赖注入(DI)和控制反转(IoC)的原理开发的. Spring Framework已经成长为控 ...
- Python基础:一、编程语言分类
编程语言主要从以下几个角度进行分类: 编译型和解释型 静态语言和动态语言 强类型语言和弱类型语言 编译型语言和解释型语言 编译和解释的区别是什么? 编译器是把源程序的每一条语句都编译成机器语言,并保存 ...
- iso系统镜像刻录到光盘和U盘
使用UltraISO刻录 刻录U盘,点击文件,打开,选择镜像 启动,写入硬盘镜像选择U盘即可 刻录光盘 工具,刻录光盘映像,选择镜像,需要先插入光盘刻录机(有些电脑可能自带光驱盘,且有刻录功能,那么我 ...
- day 44 JavaScript
一.javascript简介 JavaScript是前台语言 JavaScript是前台语言,而不是后台语言. JavaScript运行在用户的终端网页上,而不是服务器上,所以我们称为“前台语言”.J ...
- Python调用ffpmeg和ffprobe处理视频文件
需求: 运营有若干批次的视频.有上千个,视频文件,有mp4格式的,有ts格式的 现在有需要去掉视频文件片头和片尾的批量操作需求. 比如 文件夹A下面的视频去掉片尾10秒 文件夹B下面的视频去掉片头6秒 ...