Experiment 11
Experiment 11
Experiment 11
CommunicatinCommunication
Algorithm:
Server Side:
1. Create a DatagramSocket to listen on a specific port.
2. Create a byte array to store incoming data (`receiveData`).
3. Continuously loop to receive and respond to data:
- Create a DatagramPacket to receive incoming data (`receivePacket`).
- Use `DatagramSocket.receive(receivePacket)` to receive data.
- Convert received data to a String (`receivedMessage`).
- Process or display the received message.
- Extract client's IP address and port from `receivePacket`.
- Prepare a response message and convert it to bytes (`sendData`).
- Create a DatagramPacket containing `sendData`, client's IP address, and port.
- Use `DatagramSocket.send(sendPacket)` to send the response.
Client Side:
1. Create a DatagramSocket (typically without specifying a port, let OS assign).
2. Convert the message to send into bytes (`sendData`).
3. Create a DatagramPacket containing `sendData`, the server's IP address, and port.
4. Use `DatagramSocket.send(sendPacket)` to send the packet.
5. Create a byte array to store incoming data (`receiveData`).
6. Create a DatagramPacket to receive incoming data (`receivePacket`).
7. Use `DatagramSocket.receive(receivePacket)` to receive data.
8. Convert received data to a String (`receivedMessage`).
9. Process or display the received message.
10. Close the DatagramSocket.
Source code:
In Two-Way Communicatincommunication, both sides can send and receive data simultaneously.
Server Side
import java.net.*;
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String receivedMessage = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Received from client: " + receivedMessage);
Client Side
import java.net.*;
clientSocket.close();
}
}