开发者

do you think http protocol mix character stream with byte stream is not a good design

Firstly,when I say http protocol mix character stream with byte stream,I mean request head is character stream and request body is byte stream(specified by content-length ),they are seperated by an empty line.

This design make http implementation more difficult.For example,if you use java to implement an http se开发者_C百科rver,you can't use such code because BufferedReader will buffer some bytes for read a line.

InputStream   stream=socket.getInputStream();
BufferedReader reader=new BufferedReader(new InputStreamReader(stream));
String line;
while( !(line=reader.readLine()).equals("") ){
    //do something with line
}
//from stream to read content-length bytes
stream.read(...)

It would be more easy to implement http protocol if it use first two bytes to specified length of request head instead of use empty line.


It is not just bad design ... it is broken. The chances are that the BufferedReader will read the first part of the request body into its buffer. So when you read from the stream at the end, you won't get all of the body.

Once you have wrapped an InputStream you shouldn't use it directly ... especially if the wrapper does buffering.


The best way to implement this is to use an existing HTTP Server-side implementation. The Apache HTTP Components library is a good alternative to consider.

If you have to implement this yourself, then the simple solution is to:

  1. Wrap the InputStream in a BufferedInputStream.
  2. Use the BufferedInputStream to read the header lines a byte at a time and build up the lines and convert to a String yourself.
  3. Use the BufferedInputStream to read the body.

I feel that the stupid design of HTTP protocol makes the java.io library useless.

I wouldn't say that. The problem is that the HTTP protocol potentially requires a client to switch the way it interprets the characters / bytes of a request or response message halfway through the message. But if you think about it, that is not an unreasonable thing to do. The alternatives would be:

  • to send separate messages which would increase the protocol overheads, or
  • encode and send the request / response line and the headers as bytes rather than as characters.

What we really have is a tricky use-case that is too unusual to be supported in the generic java.io libraries. A protocol support library would take care of this ... if you were able to use one.


Yes, but it also would be easier to produce broken messages.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜