Java UDP socket Communication (send only)

Source: Internet
Author: User

Implementation function: The client sends a string (can be a kanji), the server side receives and displays

Server-side programs:

 PackageUdpserver;ImportJava.io.*;Importjava.net.*;/*** Service side * 1, create service + port * 2, prepare to accept container byte array * 3, package the receiving container into package Datagrampacket * 4, accept data * 5, analyze data*/   Public classserver { Public Static voidMain (string[] args)throwsIOException {//1. Create a service + portDatagramsocket Server =NewDatagramsocket (9999); //2. Prepare to accept containers        byte[] container =New byte[1024]; //3. Package Datagrampacket (byte buf[], int length)Datagrampacket packet =NewDatagrampacket (container, container.length); //4. Acceptance of data (blocked acceptance)server.receive (packet); //5. Analyze Data        byte[] data =Packet.getdata (); System.out.println (NewString (data, "Utf-8")); //6. Releasing ResourcesServer.close (); }  }

Client program:

 PackageUdpClient;ImportJava.io.*;Importjava.net.*;/*** 1, create the client + port * 2, prepare the data byte array * 3, package the data and specify the destination and port to send * 4, send * 5, Release * * think: How to deal with the type of data, such as object numbers, etc.*/   Public classClient { Public Static voidMain (string[] args)throwsIOException {//1. Create a client + portDatagramsocket client =NewDatagramsocket (8888); //2. Prepare the data byte array to be sentString msg = "UDP Programming"; byte[] data = Msg.getbytes ("Utf-8")); //3. Package The data and specify the destination and port to send Datagrampacket (byte buf[], int length, inetaddress address, int port)InetAddress address = Inetaddress.getbyname ("127.0.0.1"); Datagrampacket Packet=NewDatagrampacket (data, data.length, address, 9999); //4. Sendclient.send (packet); //5. ReleaseClient.close (); }  }

Java UDP socket Communication (send only)

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.