0% found this document useful (0 votes)
15 views1 page

UDPClient

Uploaded by

s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views1 page

UDPClient

Uploaded by

s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 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