Java Network programming UDP case

Source: Internet
Author: User

Java network programming, UDP case

Send Side

Import java.io.ioexception;import java.net.datagrampacket;import java.net.datagramsocket;import  java.net.InetAddress;import java.net.SocketException;import java.net.UnknownHostException; Public class sendudp {public static void main (String[] args) {try { Datagramsocket socket = new datagramsocket (); string str =  "Hello welcome to adm"; Byte[] buf = str.getbytes (); I Netaddress address = inetaddress.getbyaddress (Getbyteip ("192.168.1.160"));D atagrampacket  Packet = new datagrampacket (buf, buf.length,address,8888); socket.send (packet); socket.close ();}  catch  (socketexception e)  {e.printstacktrace ();}  catch  (unknownhostexception e)  {e.printstacktrace ();}  catch  (ioexception e)  {e.printstacktrace ();}} Private static byte[] getbyteip (STRING&NBSP;IP) {BYTE[]&Nbsp;ipbyte = new byte[4]; String[] strs = ip.split ("\ \"); for (int i = 0; i < ipbyte.length; i++) {ipbyte[i] =  (byte)  integer.parseint (Strs[i]);} Return ipbyte;}}

Receiving end

Import Java.io.ioexception;import Java.net.datagrampacket;import Java.net.datagramsocket;import Java.net.socketexception;public class Receiveudp {public static void main (string[] args) {Datagramsocket socket = Null;d Atagrampacket packet;byte[] buf = new Byte[1024];try {socket = new Datagramsocket (8888);p acket = new Datagrampacket (buf, b Uf.length); socket.receive (packet); Socket.close (); byte[] data = Packet.getdata (); System.out.println (new String (data, "utf-8"));} catch (SocketException e) {e.printstacktrace ()} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktra CE ();}}}


Java Network programming UDP case

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.