gpt4 book ai didi

java - Java中UDP数据报仅显示第一个字符

转载 作者:行者123 更新时间:2023-11-30 02:36:35 25 4
gpt4 key购买 nike

我正在尝试制作一个 Echo 服务器-客户端 UDP 应用程序。客户端应该发送超过 20 个号码,服务器只会将它们发回。但是,据我所知,它仅显示正在发送 String 中的第一个字符。我向我的教授寻求帮助,但他也无法弄清楚。一些帮助会很好。谢谢!

客户端.java:

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class client {
public static void main(String[] args) {
DatagramSocket socket;
try {
socket = new DatagramSocket();
InetAddress address = InetAddress.getByName("localhost");
byte[] buf = new byte[256];
for (Integer i = 1; i < 21; i++) {
buf = i.toString().getBytes();
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445);
socket.send(packet);
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
System.out.println("Server: " + received);
}
socket.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
}

服务器.java:

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class server {
public static void main(String argsp[]) {
DatagramSocket socket;
try {
socket = new DatagramSocket(4445);
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
while (true) {
socket.receive(packet);
String message = new String(packet.getData(), 0, packet.getLength());
System.out.println("Client: " + message);
buf = message.getBytes();
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(buf, buf.length, address, port);
socket.send(packet);
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

客户端输出:

Server: 1
Server: 2
Server: 3
Server: 4
Server: 5
Server: 6
Server: 7
Server: 8
Server: 9
Server: 1
Server: 1
Server: 1
Server: 1
Server: 1
Server: 1
Server: 1
Server: 1
Server: 1
Server: 1
Server: 2

服务器输出:

Client: 1
Client: 2
Client: 3
Client: 4
Client: 5
Client: 6
Client: 7
Client: 8
Client: 9
Client: 1
Client: 1
Client: 1
Client: 1
Client: 1
Client: 1
Client: 1
Client: 1
Client: 1
Client: 1
Client: 2

最佳答案

每次收到数据报时,DatagramPacket 都会缩小到指定长度。因此,在您的服务器中,第一次接收后它会缩小到 1。您需要在接收 lopo 内重新创建它,或者至少在循环顶部重置其长度。

关于java - Java中UDP数据报仅显示第一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42881457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com