Enas UDP Server:
- Κώδικας:
import java.io.*;
import java.net.*;
public class UDPServer
{
public static void main(String args[]) throws Exception
{
int bufferLength = 1024;
int listenPort = 9876;
DatagramSocket serverSocket = new DatagramSocket( listenPort );
byte[] receiveData = new byte[bufferLength];
byte[] sendData; // = new byte[bufferLength];
while (true)
{
System.out.println("Server listening to " + listenPort);
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}