Пример:
1) Помощен инструмент за конвертиране String -> DatagramPacket
DatagramPacket -> String
import java.net.*;
public class Dgram { public static DatagramPacket toDatagram(String s, InetAddress destIA, int destPort) { byte[] buf = s.getBytes(); return new DatagramPacket(buf, buf.length, destIA, destPort); } public static String toString(DatagramPacket p){ return new String(p.getData(), 0, p.getLength()); } } |
2) Сървър
import java.net.*;
import java.io.*; import java.util.*; public class DGServer {
public DGServer() {
|
System.out.println(rcvd);
String echoString = "Echoed: " + rcvd; // Extract the address and port from the // received datagram to find out where to // send it back: DatagramPacket echo = Dgram.toDatagram(echoString, dp.getAddress(), dp.getPort()); socket.send(echo); } } catch(SocketException e) { System.err.println("Can't open socket"); System.exit(1); } catch(IOException e) { System.err.println("Communication error"); e.printStackTrace(); } } public static void main(String[] args) { new DGServer(); } } |
3) Клиент
import java.lang.Thread;
import java.net.*; import java.io.*; public class DGClient extends Thread {
public DGClient(int identifier) {
|
public void run() {
try { for(int i = 0; i < 25; i++) { String outMessage = "Client #" + id + ", message #" + i; // Make and send a datagram: s.send(Dgram.toDatagram(outMessage, hostAddress, INPORT)); // Block until it echoes back: s.receive(dp); // Print out the echoed contents: String rcvd = "Client #" + id + ", rcvd from " + dp.getAddress() + ", " + dp.getPort() + ": " + Dgram.toString(dp); System.out.println(rcvd); } } catch(IOException e) { e.printStackTrace(); System.exit(1); } } public static void main(String[] args) { for(int i = 0; i < 10; i++) new DGClient(i).start(); } } |