1

嗨,我使用数据报制作了一个回显客户端 - 服务器代码。代码正在运行,从客户端发送的消息正在服务器端接收,然后它们被回显给客户端。以下场景显示了我遇到的问题

1->客户端:嗨,服务器:嗨,回显:嗨

2->Client: hello , server : hello , echoed back : hello 现在当客户端输入一条比最后一条短的消息时,会发生以下情况

3->客户端:K,服务器:Kello,回显:K

我不明白为什么服务器会打印上一条消息的其余字符,这是服务器端代码:

    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.IOException;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetAddress;
    import java.net.SocketException;
    import java.net.UnknownHostException;

    import javax.swing.SwingUtilities;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JScrollBar;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;

    public class Server extends JFrame {
int port;
// JTextField textField;
JButton resendPacket;
JTextArea chatWindow;
DatagramSocket socket;
private final int PACKET_SIZE = 124;
private final int port_Number = 6789;
DatagramPacket packet =  new DatagramPacket(new byte[PACKET_SIZE], PACKET_SIZE);

    InetAddress host;


public Server() {
    super("INSTANT ECHO - SERVER");
    resendPacket = new JButton("Echo");
    chatWindow = new JTextArea();

//  add(resendPacket, BorderLayout.SOUTH);
    add(new JScrollPane(chatWindow));
    setSize(300, 300);
    setVisible(true);
}

public void startRunning() {

    try {
        port = 6777;
        socket = new DatagramSocket(port);
        showMessage("Server is Ready... \n");
        /*resendPacket.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                // TODO Auto-generated method stub
                try {
                    socket.send(packet);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }); */
        while(true)
        {
            processPacket();
        }


    } catch (SocketException e) {
        // TODO: handle exception
        showMessage("\n Could not send packet!\n");
        e.printStackTrace();
    } 
}

private void processPacket() {




    // create a packet

    // receive a packet

    try {
        socket.receive(packet);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        showMessage("\nCould not receive Packet");
        e.printStackTrace();
    }
    try {
        socket.send(packet);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    // display the contents of the packet
    showMessage(new String(packet.getData()));



    // send the packet again to the sender

}

public void showMessage(final String text) {
    SwingUtilities.invokeLater(

    new Runnable() {

        public void run() {
            chatWindow.append("\n Packet Data : " + text);
        }
    });

}

}

这是客户端代码

    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.IOException;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetAddress;
    import java.net.SocketException;
    import java.net.UnknownHostException;

    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;

    public class Client extends JFrame {
int port = 6777;
JTextField textField;
String data = "hello" ;
// JButton sendPacket;
JTextArea chatWindow;
DatagramSocket socket;
DatagramPacket packet;
private final int PACKET_SIZE = 124;
InetAddress host;

public Client() {
    super("INSTANT ECHO - CLIENT");

    textField = new JTextField();
    try {
        host = InetAddress.getByName("127.0.0.1");
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        showMessage("\n Could not find local host");
        e.printStackTrace();
    }

尝试 {

        socket = new DatagramSocket();

    } catch (SocketException e) {
        // TODO Auto-generated catch block
        showMessage("\n Could not find Socket");
        e.printStackTrace();
    }
    // textField.setEditable(false);
    textField.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent event) {
            // TODO Auto-generated method stub
            data = event.getActionCommand();
            showMessage(event.getActionCommand());
            startRunning();
            textField.setText("");

        }
    });

    chatWindow = new JTextArea();
    add(textField, BorderLayout.SOUTH);


    add(new JScrollPane(chatWindow));
    setSize(300, 300);
    setVisible(true);

}

public void startRunning() {



    byte[] bytes_to_send = data.getBytes();

    DatagramPacket packet = new DatagramPacket(bytes_to_send,
            bytes_to_send.length, host, port);
    try {


        sendPacket(packet);
        setTime();
        receivePacket(packet);

        socket.receive(packet);
        showMessage("\n" + new String(packet.getData()));
    } catch (IOException e) {
        // TODO Auto-generated catch block

        e.printStackTrace();
    } finally {
        //closeCrap();
    }

}

private void sendPacket(DatagramPacket packet) {
    try {
        textField.setEditable(true);

        socket.send(packet);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        showMessage("\nUnable to send Packet !");
        e.printStackTrace();
    }
}

private void setTime() {
    try {
        socket.setSoTimeout(5);
    } catch (SocketException e) {
        // TODO Auto-generated catch block
        showMessage("\nRequest Time Out");
        e.printStackTrace();
    }
}

private void receivePacket(DatagramPacket packet) {
    packet = new DatagramPacket(new byte[PACKET_SIZE], PACKET_SIZE);

    try {
        socket.receive(packet);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        showMessage("\n Unable to receive packet\n");
        e.printStackTrace();
    }
    showMessage("\n Echoed Message --> "+new String(packet.getData()));
}

private void closeCrap() {
    socket.close();
}

private void showMessage(final String data) {
    SwingUtilities.invokeLater(

    new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            chatWindow.append("\n" + data);

        }
    });

}

}

谁能说出为什么要打印前面的字符?

4

2 回答 2

2

DatagramPacket.getLength()具有已使用的缓冲区的长度。

尝试

showMessage(new String(packet.getData(), 0, packet.getLength()));
于 2012-10-31T14:17:42.317 回答
0

您一遍又一遍地重用同一个数据包,因此当它从网络读取信息时,它会用新内容覆盖现有的数据包缓冲区内容。客户端没有写入空终止符,因此没有写入缓冲区。因此,当您使用showMessage(new String(packet.getData()));返回的数据打印数据时,如果刚刚收到的消息不足以完全覆盖旧内容,则其中仍有旧数据的残余。

它不会回显额外的数据,因为当您发送数据包时,套接字服从packet.getLength(),它控制要发送的字节数。

您可以:

  • 将您的 showMessage 调用更改为:

    showMessage("\n Echoed Message --> " + 
                new String(packet.getData(), 0, packet.getLength()));
    
  • 每次使用不同的数据包

任何一个都应该解决它。

于 2012-10-31T14:21:23.437 回答