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

Package UDP

This document contains a Java implementation of a UDP client that sends messages to a server running on localhost. It uses DatagramSocket for communication, allowing the user to input messages and receive responses in a continuous loop. The client constructs and sends DatagramPackets containing the user's messages and listens for replies from the server.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views1 page

Package UDP

This document contains a Java implementation of a UDP client that sends messages to a server running on localhost. It uses DatagramSocket for communication, allowing the user to input messages and receive responses in a continuous loop. The client constructs and sends DatagramPackets containing the user's messages and listens for replies from the server.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

package UDP;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class UDPClient {


public static void main(String[] args) throws Exception {
DatagramSocket cSocket = new DatagramSocket();
InetAddress serverAddress = InetAddress.getByName("localhost");
Scanner scanner = new Scanner(System.in);

while (true) {
System.out.print("To server: ");
String message = scanner.nextLine();
byte[] sendData = message.getBytes();

DatagramPacket sendPacket = new DatagramPacket(sendData,


sendData.length, serverAddress, 98);
cSocket.send(sendPacket);

byte[] receiveData = new byte[1024];


DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
cSocket.receive(receivePacket);

String response = new String(receivePacket.getData(), 0,


receivePacket.getLength());
System.out.println("Received from server: " + response);
}
}
}

You might also like