在Java中:基于UDP的客户端/服务器未提供预期的输出

时间:2014-10-16 19:35:10

标签: java udp datagram

我用Java编写了一个简单的客户端/服务器代码,其中客户端向服务器发送消息(显示在服务器的标准输出上),然后服务器也发送消息(显示在客户端& #39;标准输出)。客户端和服务器代码如下:

Client.java

import java.io.*;
import java.net.*;

public class Client {
  public static void main(String[] args)throws Exception {
    DatagramSocket socket = new DatagramSocket ();
    InetAddress address = InetAddress.getByName("127.0.0.1");

    DatagramPacket packet = null;

    BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

    byte[] buf = new byte[256];

    String msg = stdIn.readLine();

    packet = new DatagramPacket(buf, buf.length, address, 4445);
    socket.send(packet);

    // get response
    packet = new DatagramPacket(buf, buf.length);
    socket.receive(packet);

    // display response
    String received = new String(packet.getData(), 0, packet.getLength());
    System.out.println("Server says: " + received);

    socket.close();

  }
}

以下是Server.java

import java.io.*;
import java.net.*;

public class Server {
  public static void main(String[] args)throws Exception {
    DatagramSocket socket = new DatagramSocket(4445);

    byte[] buf = new byte[256];

    // receive client's message
    DatagramPacket packet = new DatagramPacket(buf, buf.length);
    socket.receive(packet);

    // display client's message
    String received = new String(packet.getData(), 0, packet.getLength());
    System.out.println("Client says: " + received);

    BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

    String msg = stdIn.readLine();

    buf = msg.getBytes();

    // send the response to the client at "address" and "port"
    InetAddress address = packet.getAddress();        
    int port = packet.getPort();
    packet = new DatagramPacket(buf, buf.length, address, port);
    socket.send(packet);
  }
}

代码编译并成功运行,但输出未达到预期效果。客户端发送的消息不会显示在服务器上,但是客户端会成功显示服务器的消息。

所以有人可以告诉可能是什么问题吗?

1 个答案:

答案 0 :(得分:2)

您永远不会使用任何有用的数据填充数据包:

byte[] buf = new byte[256];
String msg = stdIn.readLine();
packet = new DatagramPacket(buf, buf.length, address, 4445);
socket.send(packet);

您刚刚发布了一个256字节的字节数组,所有这些都是0.您完全忽略了msg。也许你想要:

String msg = stdIn.readLine();
byte[] buf = msg.getBytes(StandardCharsets.UTF_8);
packet = new DatagramPacket(buf, buf.length, address, 4445);
socket.send(packet);

这类似于您在服务器中使用的代码,毕竟......除了我明确使用UTF-8之外,我建议你做无处不在,在byte[]String之间进行转换。