Java Tutorial/Network/UDP Client

Материал из Java эксперт
Версия от 05:03, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Read and write with DatagramPacket

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Main {
  public static void main(String[] args) throws Exception {
    byte[] ary = new byte[128];
    DatagramPacket pack = new DatagramPacket(ary, 128);
    // read
    DatagramSocket sock = new DatagramSocket(1111);
    sock.receive(pack);
    String word = new String(pack.getData());
    System.out.println("From: " + pack.getAddress() + " Port: " + pack.getPort());
    System.out.println(word);
    sock.close();
    // write
    sock = new DatagramSocket();
    pack.setAddress(InetAddress.getByName(args[1]));
    pack.setData(args[2].getBytes());
    pack.setPort(1111);
    sock.send(pack);
    sock.close();
  }
}





Receiving a Datagram

import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class Main {
  public static void main(String[] argv) throws Exception {
    byte[] inbuf = new byte[256]; // default size
    DatagramSocket socket = new DatagramSocket();
    DatagramPacket packet = new DatagramPacket(inbuf, inbuf.length);
    socket.receive(packet);
    int numBytesReceived = packet.getLength();
    System.out.println(numBytesReceived);
  }
}





Send a Datagram

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class Main {
  public static void main(String[] argv) throws Exception {
  }
  public static void senddatagram(InetAddress target, int port, byte[] outbuf, int len) {
    try {
      DatagramPacket request = new DatagramPacket(outbuf, len, target, port);
      DatagramSocket socket = new DatagramSocket();
      socket.send(request);
    } catch (SocketException e) {
    } catch (IOException e) {
    }
  }
}





Sending a Datagram

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Main {
  public static void main(String[] argv) throws Exception {
    InetAddress dst = InetAddress.getLocalHost();
    int port = 8080;
    byte[] outbuf = new byte[1024];
    int len = 1024;
    DatagramPacket request = new DatagramPacket(outbuf, len, dst, port);
    DatagramSocket socket = new DatagramSocket();
    socket.send(request);
  }
}





UDP Discard Client

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class MainClass {
  public static void main(String[] args) throws Exception {
    InetAddress server = InetAddress.getByName("localhost");
    BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
    DatagramSocket theSocket = new DatagramSocket();
    while (true) {
      String theLine = userInput.readLine();
      if (theLine.equals("."))
        break;
      byte[] data = theLine.getBytes();
      DatagramPacket theOutput = new DatagramPacket(data, data.length, server, 99999);
      theSocket.send(theOutput);
    }
  }
}





UDP Echo Client

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class MainClass {
  public static void main(String[] args) throws Exception {
    String hostname = "localhost";
    InetAddress ia = InetAddress.getByName(hostname);
    SenderThread sender = new SenderThread(ia, 1919);
    sender.start();
    Thread receiver = new ReceiverThread(sender.getSocket());
    receiver.start();
  }
}
class SenderThread extends Thread {
  private InetAddress server;
  private DatagramSocket socket;
  private boolean stopped = false;
  private int port;
  public SenderThread(InetAddress address, int port) throws SocketException {
    this.server = address;
    this.port = port;
    this.socket = new DatagramSocket();
    this.socket.connect(server, port);
  }
  public void halt() {
    this.stopped = true;
  }
  public DatagramSocket getSocket() {
    return this.socket;
  }
  public void run() {
    try {
      BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
      while (true) {
        if (stopped)
          return;
        String theLine = userInput.readLine();
        if (theLine.equals("."))
          break;
        byte[] data = theLine.getBytes();
        DatagramPacket output = new DatagramPacket(data, data.length, server, port);
        socket.send(output);
        Thread.yield();
      }
    }
    catch (IOException ex) {
      System.err.println(ex);
    }
  }
}
class ReceiverThread extends Thread {
  DatagramSocket socket;
  private boolean stopped = false;
  public ReceiverThread(DatagramSocket ds) throws SocketException {
    this.socket = ds;
  }
  public void halt() {
    this.stopped = true;
  }
  public void run() {
    byte[] buffer = new byte[65507];
    while (true) {
      if (stopped)
        return;
      DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
      try {
        socket.receive(dp);
        String s = new String(dp.getData(), 0, dp.getLength());
        System.out.println(s);
        Thread.yield();
      } catch (IOException ex) {
        System.err.println(ex);
      }
    }
  }
}





UDP Time Client

import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.DatagramChannel;
public class UDPTimeClient {
  public static void main(String[] args) throws Exception {
    DatagramChannel channel = DatagramChannel.open();
    // port 0 selects any available port
    SocketAddress address = new InetSocketAddress(0);
    DatagramSocket socket = channel.socket();
    socket.setSoTimeout(5000);
    socket.bind(address);
    SocketAddress server = new InetSocketAddress("time.nist.gov", 37);
    ByteBuffer buffer = ByteBuffer.allocate(8192);
    // time protocol always uses big-endian order
    buffer.order(ByteOrder.BIG_ENDIAN);
    // Must put at least one byte of data in the buffer;
    // it doesn"t matter what it is.
    buffer.put((byte) 65);
    buffer.flip();
    channel.send(buffer, server);
    buffer.clear();
    buffer.put((byte) 0).put((byte) 0).put((byte) 0).put((byte) 0);
    channel.receive(buffer);
    buffer.flip();
    long secondsSince1970 = buffer.getLong();
    System.out.println(secondsSince1970);
    channel.close();
  }
}





User Datagram Protocol Programming

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Main {
  final private static int DAYTIME_PORT = 13;
  public static void main(String args[]) throws IOException {
    String host = args[0];
    byte message[] = new byte[256];
    InetAddress address = InetAddress.getByName(host);
    System.out.println("Checking at: " + address);
    DatagramPacket packet = new DatagramPacket(message, message.length, address, DAYTIME_PORT);
    DatagramSocket socket = new DatagramSocket();
    socket.send(packet);
    packet = new DatagramPacket(message, message.length);
    socket.receive(packet);
    String time = new String(packet.getData());
    System.out.println(time);
    socket.close();
  }
}