我想通过服务器将数据从一个客户端发送到另一个客户端DatagramSocket class
。服务器从客户端接收数据,将客户端端口号和名称添加到数组列表中,但不将数据发送到目标客户端。如何让服务器监听服务器发送的数据??不只是在按下任何按钮时接收数据。服务器包含“while循环”来监听客户端,我怎样才能在客户端做到这一点?
客户端类:
public class DatagramClient extends JFrame {
private JTextField jtf = new JTextField();
private JTextArea jta = new JTextArea();
private DatagramSocket socket;
private byte[] buf = new byte[256];
private InetAddress address;
private DatagramPacket sendPacket;
private DatagramPacket receivePacket;
public static void main(String[] args) {
new DatagramClient();
}
public DatagramClient() {
//GUI
jtf.addActionListener(new ButtonListener()); // Register listener
try {
socket = new DatagramSocket();
address = InetAddress.getByName("localhost");
sendPacket =
new DatagramPacket(buf, buf.length, address, 8000);
receivePacket = new DatagramPacket(buf, buf.length);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
Arrays.fill(buf, (byte)0);
sendPacket.setData(jtf.getText().trim().getBytes());
socket.send(sendPacket);
socket.receive(receivePacket);
jta.append("Radius is " + jtf.getText().trim() + "\n");
jta.append("Area received from the server is "
+ Double.parseDouble(new String(buf).trim()) + '\n');
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
服务器类:
public class DatagramServer extends JFrame {
private JTextArea jta = new JTextArea();
private byte[] buf = new byte[256];
ArrayList<Integer> clientPort=new ArrayList<Integer>();
ArrayList<String> clientName=new ArrayList<String>();
public static void main(String[] args) {
new DatagramServer();
}
public DatagramServer() {
//GUI
try {
DatagramSocket socket = new DatagramSocket(8000);
jta.append("Server started at " + new Date() + '\n');
DatagramPacket receivePacket =
new DatagramPacket(buf, buf.length);
DatagramPacket sendPacket ;
while (true) {
clientPort.add(receivePacket.getPort);
clientName.add( receivePacket.getAddress().getHostAddress());
Arrays.fill(buf, (byte)0);
socket.receive(receivePacket);
jta.append("The client host name is "+receivePacket.getAddress().getHostAddress() +
" and port number is " + receivePacket.getPort() + '\n');
jta.append("Radius received from client is " +
new String(buf).trim() + '\n');
double radius = Double.parseDouble(new String(buf).trim());
double area = radius * radius * Math.PI;
jta.append("Area is " + area + '\n');
InetAddress addr=InetAddress.getByName(clientName.get(0));
sendPacket = new DatagramPacket(buf, buf.length);
sendPacket.setAddress(addr);
sendPacket.setAddress(clientPort.get(0));
sendPacket.setData(new Double(area).toString().getBytes());
socket.send(sendPacket);
}
}
catch(IOException ex) {
ex.printStackTrace();
}
}