java - 如何让 UDP 服务器响应 UDP 客户端数据包?
问题描述
我无法让服务器将数据发送回客户端。这是我的代码以及我的输入和结果。
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?");
}
}
}
我不确定为什么服务器不回显给客户端?我不确定我做错了什么,或者这段代码的整体质量。
解决方案
服务器正在向自己发送回复。当您sendPacket
在服务器中创建时,您将提供它ip
,port
但ip
andport
是服务器自己的 IP 和绑定(侦听)端口,而不是客户端的端口。
因为客户端创建它DatagramSocket
时没有指定端口,系统会动态地为其选择一个未使用的端口号。您需要使用receivePacket.getSocketAddress()
(在服务器中)获取客户端的端口号,然后在构建sendPacket
. 事实上,有一个替代构造函数DatagramPacket
可以接受缓冲区、长度,SocketAddress
并且非常适合构造回复数据包。
推荐阅读
- c# - 调用 Graph API URL 时出现异常
- vuejs2 - 将表单数据添加到后端时出现 CORS 问题
- java - 如何获得正确的输入来获取我的 ArrayList 的索引?
- arrays - 以随机顺序创建具有数字 1-16 的二维数组
- sql - ST_HexagonGrid 几何向量查找所有点
- java - 实现从 autcloseable 扩展的接口的类
- typescript - 如何建立一个“测试端口”,通过它选择的私有功能将是公开的?
- bash - BASH:让多个 bash 后台进程写入同一个文件是否安全?
- reactjs - React - 通过路由器更改组件
- python - 使用 groupby 并创建具有百分比频率的列