UDP Send article data gram packet to given host. - Java Network

Java examples for Network:UDP

Description

UDP Send article data gram packet to given host.

Demo Code


//package com.java2s;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class Main {
    public static void main(String[] argv) throws Exception {
        String host = "java2s.com";
        int port = 2;
        String article = "java2s.com";
        send(host, port, article);//from ww w  .j  av  a  2s . co m
    }

    /**
     * Send article data gram packet to given host.
     *   
     * @param host
     * @param port
     * @param article
     * @throws IOException
     */
    public static void send(String host, int port, String article)
            throws IOException {

        DatagramSocket socket = new DatagramSocket();

        InetAddress addr = InetAddress.getByName(host);

        byte[] data = article.getBytes();
        DatagramPacket packet = new DatagramPacket(data, 0, data.length,
                addr, port);

        socket.send(packet);
        socket.close();

    }
}

Related Tutorials