Basic ClientServer Communication using UDP Datagram
suggest changeClient.java
import java.io.*;
import java.net.*;
public class Client{
public static void main(String [] args) throws IOException{
DatagramSocket clientSocket = new DatagramSocket();
InetAddress address = InetAddress.getByName(args[0]);
String ex = "Hello, World!";
byte[] buf = ex.getBytes();
DatagramPacket packet = new DatagramPacket(buf,buf.length, address, 4160);
clientSocket.send(packet);
}
}
In this case, we pass in the address of the server, via an argument (args[0]). The port we are using is 4160.
Server.java
import java.io.*;
import java.net.*;
public class Server{
public static void main(String [] args) throws IOException{
DatagramSocket serverSocket = new DatagramSocket(4160);
byte[] rbuf = new byte[256];
DatagramPacket packet = new DatagramPacket(rbuf, rbuf.length);
serverSocket.receive(packet);
String response = new String(packet.getData(), packet.getOffset(), packet.getLength());
System.out.println("Received: " + response);
}
}
On the server, open a DatagramSocket on the same port the client sends to (4160) and wait for a datagram. getData() is the whole receive buffer; only getOffset() and getLength() are the bytes that arrived. The socket is not closed in this sketch.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents