Java/Network Protocol/DatagramSocket

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

Datagram Sender

 
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
class DatagramSender {
  public static void main(String args[]) throws Exception {
    InetAddress ia = InetAddress.getByName(args[0]);
    // Obtain destination port
    int port = Integer.parseInt(args[1]);
    // Create a datagram socket
    DatagramSocket ds = new DatagramSocket();
    // Create a datagram packet
    byte buffer[] = args[2].getBytes();
    DatagramPacket dp = new DatagramPacket(buffer, buffer.length, ia, port);
    ds.send(dp);
  }
}





DatagramSocket receives DatagramPacket

 
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class Main {
  public static void main(String[] args) throws Exception {
    DatagramSocket ds = new DatagramSocket(3000);
    byte[] buf = new byte[1024];
    DatagramPacket dp = new DatagramPacket(buf, 1024);
    ds.receive(dp);
    String strRecv = new String(dp.getData(), 0, dp.getLength()) + " from "
        + dp.getAddress().getHostAddress() + ":" + dp.getPort();
    System.out.println(strRecv);
    ds.close();
  }
}





DatagramSocket sends out DatagramPacket

 
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Main {
  public static void main(String[] args) throws Exception {
    DatagramSocket ds = new DatagramSocket();
    String str = "hello world";
    InetAddress ia = InetAddress.getByName("127.0.0.1");
    DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ia, 3000);
    ds.send(dp);
    ds.close();
  }
}





Joining a Multicast Group

 
import java.net.InetAddress;
import java.net.MulticastSocket;
public class Main {
  public static void main(String[] argv) throws Exception {
    String groupName = "groupName";
    int port = 1024;
    MulticastSocket msocket = new MulticastSocket(port);
    InetAddress group = InetAddress.getByName(groupName);
    msocket.joinGroup(group);
  }
}





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();
  }
}





Receive DatagramPacket

 
import java.net.DatagramPacket;
import java.net.DatagramSocket;
class Collector {
  private final static int BUFSIZE = 20;
  public static void main(String args[]) throws Exception {
    int port = Integer.parseInt(args[0]);
    DatagramSocket ds = new DatagramSocket(port);
    while (true) {
      byte buffer[] = new byte[BUFSIZE];
      DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
      ds.receive(dp);
      System.out.println(new String(dp.getData()));
    }
  }
}





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);
  }
}





Receiving from a Multicast Group

 

import java.net.DatagramPacket;
import java.net.MulticastSocket;
public class Main {
  public static void main(String[] argv) throws Exception {
    MulticastSocket msocket = new MulticastSocket(9999);
    byte[] inbuf = new byte[1024];
    DatagramPacket packet = new DatagramPacket(inbuf, inbuf.length);
    msocket.receive(packet);
    // Data is now in inbuf
    int numBytesReceived = packet.getLength();
  }
}





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) {
    }
  }
}





Send back the response in a DatagramPacket

 

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Date;
public class Main {
  final private static int DAYTIME_PORT = 13;
  public static void main(String args[]) throws IOException {
    DatagramSocket socket = new DatagramSocket(DAYTIME_PORT);
    while (true) {
      byte buffer[] = new byte[256];
      DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
      socket.receive(packet);
      String date = new Date().toString();
      buffer = date.getBytes();
      // Get response address/port for client from packet
      InetAddress address = packet.getAddress();
      int port = packet.getPort();
      packet = new DatagramPacket(buffer, buffer.length, address, port);
      socket.send(packet);
    }
  }
}





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);
  }
}





Sending to a Multicast Group

 
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Main {
  public static void main(String[] argv) throws Exception {
    byte[] outbuf = new byte[1024];
    int port = 1234;
    DatagramSocket socket = new DatagramSocket();
    InetAddress groupAddr = InetAddress.getByName("8.1.2.3");
    DatagramPacket packet = new DatagramPacket(outbuf, outbuf.length, groupAddr, port);
    socket.send(packet);
  }
}





Use DatagramSocket to send out and receive DatagramPacket

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class ChatClient {
  public static void main(String[] args) throws Exception {
    DatagramSocket s = new DatagramSocket();
    byte[] buf = new byte[1000];
    DatagramPacket dp = new DatagramPacket(buf, buf.length);
    InetAddress hostAddress = InetAddress.getByName("localhost");
    while (true) {
      BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
      String outMessage = stdin.readLine();
      if (outMessage.equals("bye"))
        break;
      String outString = "Client say: " + outMessage;
      buf = outString.getBytes();
      DatagramPacket out = new DatagramPacket(buf, buf.length, hostAddress, 9999);
      s.send(out);
      s.receive(dp);
      String rcvd = "rcvd from " + dp.getAddress() + ", " + dp.getPort() + ": "
          + new String(dp.getData(), 0, dp.getLength());
      System.out.println(rcvd);
    }
  }
}

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class ChatServer {
  public static void main(String[] args) throws Exception {
    int PORT = 4000;
    byte[] buf = new byte[1000];
    DatagramPacket dgp = new DatagramPacket(buf, buf.length);
    DatagramSocket sk;
    sk = new DatagramSocket(PORT);
    System.out.println("Server started");
    while (true) {
      sk.receive(dgp);
      String rcvd = new String(dgp.getData(), 0, dgp.getLength()) + ", from address: "
          + dgp.getAddress() + ", port: " + dgp.getPort();
      System.out.println(rcvd);
      
      BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
      String outMessage = stdin.readLine();
      buf = ("Server say: " + outMessage).getBytes();
      DatagramPacket out = new DatagramPacket(buf, buf.length, dgp.getAddress(), dgp.getPort());
      sk.send(out);
    }
  }
}





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();
  }
}