Java TCP / IP Socket Programming Notes (4) - send and receive data

2009-02-03  来源:本站原创  分类:Java  人气:626 

1.TCP/IP agreement calls for information must be in the block (chunk) to send and receive, while the block length must be a multiple of 8 bits, therefore, we can assume that TCP / IP protocol to transmit the message that byte sequence. How to send and parse the information needs of a certain application protocol.
2. Information coding:
The first is Java, the basic integer processing, sending, we should pay attention: 1) the number of bytes for each data type; 2) The order of bytes to send what is it? (Little-endian or big-endian); 3) the transmission of values is a sign of the (signed) or unsigned (unsigned). Specific codes used bit operations (shift and shielding) on it. Specifically in Java, can be used to achieve the DataOutputStream classes and ByteArrayOutputStream. Recovery can be used DataInputStream class and ByteArrayInputStream class.
Second, the string and text, in a group of symbols and the mapping between a set of integers known as the coded character set (coded character set). The sender and the recipient must be an integer mapping symbols and to reach a consensus in order to use text messaging to communicate, the easiest way is to define a standard character set. The specific use of String to encode the getBytes () method.
Finally, the bit operation. If you set a specific set to 1, first set up the mask (mask), after the use or operation; To clear a specific one, use and operation.
3. Framing and analytic framing (framing) technology to solve how to position the receiving end of the first location of the message problem.
If the receiver attempts to read from the socket more bytes than the message itself will be one of the following two situations may occur: If there are no other news channel, the receiver will be blocked waiting for the same time, unable to handle received messages ; if the sender is also waiting for the receiving end of the response messages, it will form a deadlock (dealock); other hand, if there are other news channel, then the receiver will be back some or all of the message read the first message in go, which would have some protocol error. Therefore, the use of TCP socket, the framing is a very important factor for consideration.
There are two technologies:
1. Based on the delimiter (Delimiter-based): the end of the message by a unique tag (unique marker) that is sent in the transmission data is finished explicitly add a special byte sequence. This special tag can not appear in the transmitted data. Fortunately, the fill (stuffing) technology can appear in the message delimiter be modified so that the recipient does not recognize it as a delimiter. Delimiter when scanning at the receiver, but also to identify the modified data, and in the output messages to restore them, making it consistent with the original message.
2. Explicit Length (Explicit length): In the variable-length field or message attached to a fixed size of the previous field, is used to direct the field or the message contains the number of bytes. This method to determine the maximum length of the message to determine the need to preserve the length of the number of bytes.
Interface:

import java.io.IOException;
import java.io.OutputStream;

public interface Framer {
        void frameMsg(byte [] message,OutputStream out) throws IOException;
        byte [] nextMsg() throws IOException;
}

Delimiter ways:

import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class DelimFramer implements Framer {
        private InputStream in;//data source;
        private static final byte DELIMTER=(byte)'\n';//message delimiter

        public DelimFramer(InputStream in){
                this.in=in;
        }

        @Override
        public void frameMsg(byte[] message, OutputStream out) throws IOException {
                //ensure that the message dose not contain the delimiter
                for(byte b:message){
                        if(b==DELIMTER)
                                throw new IOException("Message contains delimiter");
                }
                out.write(message);
                out.write(DELIMTER);
                out.flush();

        }

        @Override
        public byte[] nextMsg() throws IOException {
                ByteArrayOutputStream messageBuffer=new ByteArrayOutputStream();
                int nextByte;

                while((nextByte=in.read())!=DELIMTER){
                        if(nextByte==-1){//end of stream?
                                if(messageBuffer.size()==0){
                                        return null;
                                }else{
                                        throw new EOFException("Non-empty message without delimiter");
                                }
                        }
                        messageBuffer.write(nextByte);
                }
                return messageBuffer.toByteArray();
        }
}

Explicit length method:

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class LengthFramer implements Framer {
        public static final int MAXMESSAGELENGTH=65535;
        public static final int BYTEMASK=0xff;
        public static final int SHOTMASK=0xffff;
        public static final int BYTESHIFT=8;

        private DataInputStream in;// wrapper for data I/O

        public LengthFramer(InputStream in) throws IOException{
                this.in=new DataInputStream(in);
        }

        @Override
        public void frameMsg(byte[] message, OutputStream out) throws IOException {
                if(message.length>MAXMESSAGELENGTH){
                        throw new IOException("message too long");
                }

                //write length prefix
                out.write((message.length>>BYTEMASK)&BYTEMASK);
                out.write(message.length&BYTEMASK);
                //write message
                out.write(message);
                out.flush();
        }

        @Override
        public byte[] nextMsg() throws IOException {
                int length;

                try{
                        length=in.readUnsignedShort();
                }catch(EOFException e){
                        //no (or 1 byte) message;
                        return null;
                }
                //0<=length<=65535;
                byte [] msg=new byte[length];
                in.readFully(msg);//if exception,it's a framing error;
                return msg;
        }
}
相关文章
  • Java TCP / IP Socket Programming Notes (4) - send and receive data 2009-02-03

    1.TCP/IP agreement calls for information must be in the block (chunk) to send and receive, while the block length must be a multiple of 8 bits, therefore, we can assume that TCP / IP protocol to transmit the message that byte sequence. How to send an

  • Java TCP / IP Socket Programming Notes (1) - the basic concept 2009-09-12

    Some concepts: Communication channel (communication channel): a sequence of bytes transmitted from one host to another host as a means may be wired cable, such as Ethernet (Ethernet), it may be wireless, such as WiFi, or other means connections. Info

  • Java TCP / IP Socket Programming Notes (3)-UDP example 2010-04-29

    1.UDP sockets and TCP sockets different. UDP sockets do not need to connect before use. TCP protocol and telephone communications, similar to the UDP protocol is similar to communicate with the e-mail: You Do not send packages or letters to "connect&

  • Java TCP / IP Socket Programming Notes (2)-TCP example 2009-08-11

    1.InetAddress classes and SocketAddress used to identify network hosts TCP protocol client and server-side socket as Socket and ServerSocket UDP protocol client and server-side socket as a DatagramSocket 2. Class NetworkInterface said a name and assi

  • 10. Network programming (TCP / IP.Socket programming. C / S) 2010-03-28

    1. What is the concept of network infrastructure, computer network: The distributed in different geographical regions of the external computer equipment and specialized communications lines interconnected into a large-scale, functionally efficient ne

  • linux IP socket programming (translation) unfinished, continued 2010-04-09

    About this tutorial: IP sockets are high-level Internet protocols to establish the bottom - all HTTP, SSL, POP3, Kerberos and UDP-Time interaction between the protocol are based on this. To control agreement, a programmer should have knowledge of the

  • TCP / IP SOCKET HTTP (Zhuantie) 2011-01-12

    Seven, respectively, from bottom to top the network for the physical layer, data link layer, network layer, transport layer, session layer, presentation layer and application layer. In which the physical layer, data link layer and network layer is of

  • linux IP socket programming (translation) 2010-04-09

    About this tutorial: IP sockets are high-level Internet protocols to establish the bottom - all HTTP, SSL, POP3, Kerberos and UDP-Time interaction between the protocol are based on this. To control agreement, a programmer should have knowledge of the

  • TCP/IP Socket 2013-01-21

    Local socket address: Local IP address and port number Remote socket address: Only for established TCP sockets. As discussed in the client-server section below, this is necessary since a TCP server may serve several clients concurrently. The server c

  • Android TCP/IP Socket Test 2014-11-01

    TCP/IP协议:Transmission Control Protocol/Internet Protocol的简写,中译名为传输控制协议/因特网互联协议,又名网络通讯协议,是Internet最基本的协议.Internet国际互联网络的基础,由网络层的IP协议和传输层的TCP协议组成.TCP/IP 定义了电子设备如何连入因特网,以及数据如何在它们之间传输的标准.协议采用了4层的层级结构,每一层都呼叫它的下一层所提供的网络来完成自己的需求.通俗而言:TCP负责发现传输的问题,一有问题就发出信号,

  • TCP/IP协议,HTTP协议 2014-06-11

    1. 协议 a. TCP/IP整体构架概述 TCP/IP协议并不完全符合OSI的七层参考模型.传统的开放式系统互连参考模型,是一种通信协议的7层抽象的参考模型,其中每一层执行某一特定任务.该模型的目的是使各种硬件在相同的层次上相互通信.这7层是:物理层.数据链路层.网路层.传输层.话路层.表示层和应用层.而TCP/IP通讯协议采用了4层的层级结构,每一层都呼叫它的下一层所提供的网络来完成自己的需求.这4层分别为: i. 应用层:应用程序间沟通的层,如超文本传送协议(HTTP).简单电子邮件传输(

  • java socket programming practice of reference (translation) 2010-04-22

    Keywords: socket, flush, blocking, timeout, serversocket, flow, shutdown socket / socket Sockets let you send raw streams of bytes back and forth between two computers, giving you fairly low-level access to the TCP / IP protocol. See the File I / O A

  • Based on the UDP and TCP Socket Programming Introduction 2010-07-15

    Trackback URI http://hi.baidu.com/luohb2325/blog/item/257a19d0d44448339a502771.html I. Introduction TCP (Transmission Control Protocol) and UDP (User Datagram Protocol is a network architecture, TCP / IP transport layer a layer of two different commu

  • Socket Programming Guide and sample programs 2010-06-05

    1 Introduction In some common programming techniques, Socket Network programming can be described as the simplest. Socket programming and very little basic knowledge needed for beginners to learn network programming. Currently supports network transm

  • Linux Socket Programming Environment 2010-09-26

    What is Socket Socket interface is a TCP / IP network, API, Socket Interface defines a number of functions or routines that programmers can use them to develop TCP / IP network applications. To learn on the Internet TCP / IP network programming, we m

  • socket programming principle 2010-11-25

    socket programming principle The introduction of a problem UNIX system I / O command set, from Maltics and early evolution of the system out of order, the mode to open a read / write a closed (open-write-read- close). Processes in a user I / O operat

  • ActionScript 3.0 Socket programming 2010-04-14

    Programming using ActionScript3.0 time to note the following issues: 1, and Socket server connection. 2, the server sends data to the Socket. 3, reading data from the Socket server. 4, shook hands with the Socket server and determine what kind of dat

  • Flex ActionScript3.0 Socket Programming 2010-09-09

    ActionScript3.0 Socket Programming (0) We carried out using ActionScript3.0 Socket programming problem when the need to focus on the following, we will study one by one in the future on the following issues are discussed, and possible improvements in

  • Summary of socket programming 2011-01-11

    Socket based on TCP / IP protocol basis, can be seen as connected at both ends of the communication transceivers, servers and clients to send and receive data through the Socket. In addition to the first Socket constructor with no parameters, other s

  • TCP / IP transport layer, you know how much? 2011-05-12

    You do not know the transport layer Inscription: 23-page document, the brim of the filled notes, paper stuff, always afraid of losing, or choose to sum it up to the blog. PS. The old rules, lists 20 questions that may be encountered, if you can answe