UDP-based transmission of Android socket

Source: Internet
Author: User

Steps for creating a receiver:

1. Create an initramsocket object and specify the listening port number.

Datagramsocket socket = new datagramsocket (4567 );

2. Create a byte array for receiving

Byte data [] = new byte [1024];

3. Create an empty initrampackage object

Required rampackage package = new required rampackage (data, data. Length );

4. Use the receive method to receive the data sent by the sender, which is also a blocking method.

Socket. Receive (Package );

5. Get the sent data

New String (package. getdata (), package. getoffset (), package. getlength ());

 

Sender creation steps:

1. Create a initramsocket object

Datagramsocket socket = new datagramsocket (4567 );

2. Create an inetaddress, equivalent to the address

Inetaddress serveraddress = inetaddress. getbyname ("the IP address to be sent ");

3. This is to send a random data

String STR = "hello ";

4. Convert to byte type

Byte data [] = Str. getbytes ();

5. Create an initrampacket object and specify the address to which the packet is sent to the network and the port number.

Datagrampacket package = new datagrampacket (data, data. length, serveraddress, 4567 );

6. Call the send method of the initramsocket object to send data.

Socket. Send (Package );

Related Article

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.