Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

UDPClient

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 1

import java.io.

*;
import java.net.*;

class UDPClient {
public static void main(String[] args) {
try (DatagramSocket clientSocket = new DatagramSocket()) {
InetAddress serverIPAddress = InetAddress.getByName("localhost");
byte[] sendData;
byte[] receiveData = new byte[1024];

// Set up user input


BufferedReader inFromUser = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter a sentence: ");
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();

// Create packet to send data to server


DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, serverIPAddress, 9876);
clientSocket.send(sendPacket);

// Create packet to receive data from server


DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData(), 0,
receivePacket.getLength());

// Print the server's response


System.out.println("FROM SERVER: " + modifiedSentence);
} catch (IOException e) {
System.err.println("Error in UDP Client: " + e.getMessage());
}
}
}

You might also like