作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我无法让服务器将数据发送回客户端。这是我的代码以及我的输入和结果。
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
和 port
是服务器自己的IP和绑定(bind)(监听)端口,而不是你客户端的端口。
由于客户端在创建其DatagramSocket
时未指定端口,因此系统会为其动态选择一个未使用的端口号。您需要使用 receivePacket.getSocketAddress()
(在服务器中)获取客户端的端口号,然后在构造 sendPacket
时使用该地址。事实上,DatagramPacket
有一个替代构造函数,它接受缓冲区、长度和 SocketAddress
,这是构建回复数据包的理想选择。
关于java - 如何让UDP服务器响应UDP客户端数据包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50050991/
我是一名优秀的程序员,十分优秀!