У меня проблемы с тем, чтобы заставить сервер отправлять данные обратно клиенту. Вот мой код, мои данные и результаты.
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPServer {
public static void main(String[] args) throws IOException {
InetAddress ip = InetAddress.getByName("127.0.0.1");
int port = 1345;
//Creates connection socket.
DatagramSocket serverSocket = new DatagramSocket(port);
System.out.println("Server Active");
while(true) {
//Receiving packet
byte[] buffer = new byte[100];
DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
serverSocket.receive(receivePacket);
String clientInput = new String(buffer);
System.out.println("Server has Received : " + clientInput);
//Sending packet
byte[] data = clientInput.getBytes();
DatagramPacket sendPack = new DatagramPacket(data, data.length, ip, port);
serverSocket.send(sendPack);
String serverInput = new String(data);
System.out.println("Server has sent: " + serverInput);
}
}
}
~~~~~~~~~~~~~~~~~
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramSocket;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
public class UDPClient
{
public static void main(String args[]) throws IOException
{
DatagramSocket clientSocket = new DatagramSocket();
InetAddress ip = InetAddress.getByName("127.0.0.1");
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
int port = 1345;
System.out.println("Would you like to continue?");
while(inFromUser.readLine().equals("Yes") || inFromUser.readLine().equals("yes")) {
System.out.println("Enter an expression to be evaluated");
//gets userInput
String userInput = inFromUser.readLine();
byte[] buffer = userInput.getBytes();
//sends packet to server
DatagramPacket sendPacket = new DatagramPacket(buffer, buffer.length, ip, port);
clientSocket.send(sendPacket);
System.out.println("Client has sent: " + userInput);
//receives packet from server
byte[] data = new byte[100];
DatagramPacket receivePacket = new DatagramPacket(data, data.length);
clientSocket.receive(receivePacket);
String serverInput = new String(data);
System.out.println("Client has received: " + serverInput);
System.out.println("Would you like to continue?");
}
}
}
Я не уверен, почему сервер не отвечает клиенту? Я не уверен, что я делаю неправильно или в отношении общего качества этого кода.