Byte array data transfer in socket

Source: Internet
Author: User
Client:
private socket socket;
Private DataOutputStream out;

out = new DataOutputStream (Socket.getoutputstream ()); 
byte[] bytes = {0x03,0x02,0x01};
Out.write (bytes);

Server side:
Private Socket Clientsocket;
Private DataInputStream in;

in = new DataInputStream (Clientsocket.getinputstream ());
Defines a byte array to hold the read data, and the byte array is long enough.
byte[] bytes = new byte[100];
In.read (bytes)//writes the input stream data to the bytes array. Then read it in turn

string string = new string (bytes,index,length);
Integer integer = new Integer (New String (bytes,index,length));
Converts the byte in the byte array from the length of the beginning of index to the string type.
//new String (byte) converts the entire byte array to a String type.

Note: The socketclient output stream and the Socketserver input stream must be of the same flow (e.g. Datainputsteam and Dataoutputsteam, Inputsteam, and Outputsteam)
The DataOutputStream stream above is stored in bytes into a byte array, and the new string method can be used to convert it to a string type. The use of printwriter as compared to cumbersome, encapsulates a number of methods that are inconvenient to convert between byte and string.
Reference: http://blog.sina.com.cn/s/blog_a4bfe8c90101dpst.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.