Original: http://blog.sina.com.cn/s/blog_726233070100nqw7.html
Explain the Android socket, including the process of getting packets, unpacking, unpacking.
Sometimes the application needs to send and receive some data from the network, the bottom of the software is a socket internship, the Android operating system kernel is Linux, the development language is Java, just the data storage structure and the server size header is built in C is the opposite, so take to C server data , you need to convert the size header of the data. This is also explained here.
First, the socket.
Instantiate a socket (specify the server IP and port number to establish a valid TCP/IP connection)
Socket socket = new Socket (String ip,int port);
Note that the process of a socket for a socket instance is blocked, and it is necessary to complete the worker thread
Get Socketstream
OutputStream OutStream = Socket.getoutputstream ();
InputStream InputStream = Socket.getinputstream ();
Here is a few words, socketstream as long as not close, the socket will be connected, that is, we call the long connection
The input and output stream is defined as: from the stream input to the memory, called the input stream, and vice versa.
Flow is the equivalent of a pipe, there is no data, with the flow itself has no relationship
Send a group of byte[] out
OutStream. Write (b, 0, Len);
B is a set of byte (a byte=16bit in Java, in the order of the large head in the previous index (also called a cursor) starting from 0 to Len End
OutStream. Flush ();
Update the channel of a stream
Accept byte[] and unpacking Note: The header here is 4 bytes, the first 2 bytes is length, and the last two bytes is type
int leftlength = 0;
Byte[] B = new byte[4096];
while ((Leftlength + = Inputstream.read (b, Leftlength, 2048)) > 0) {
Read is a blocked thread, so there is no need to consider a dead loop here, with data returning the value >0
LOG.E (">>>>>>>>>>>>>>>>>>>>>>>>", " Leftlength >>> leftlength = "+ leftlength);
Start unpacking here
while (true) {
if (Leftlength < 4)
Break
else {
int length = Bytehandle.getshort (b, 0);
if (length <= leftlength) {
int type = Bytehandle.getshort (b, 2);
byte[] buf = new Byte[length];
System.arraycopy (b, 0, buf, 0, length);
System.arraycopy (b, length, B, 0, leftlength-length);
Leftlength-= length;
Switch (type) {
Case REG_REQ_CNF_MSG:
Android Socket Network data transfer