简体   繁体   English

为什么receive()方法不从客户端接收数据?

[英]Why receive() method doesn't receive data from client?

I wrote small client-server application. 我写了小的客户端服务器应用程序。 It should send one string from client to server and server should show it on console. 它应该从客户端向服务器发送一个字符串,服务器应在控制台上显示它。 But server waits for data all time. 但是服务器一直在等待数据。 It looks like data don't come to server. 看来数据没有到达服务器。 What did i wrong? 我怎么了

public class UDPClient {

    public static void main(String[] args) throws IOException {
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
        DatagramSocket clientSocket = new DatagramSocket();
        InetAddress IPAdress = InetAddress.getByName("localhost");
        byte[] sendData = new byte[1024];
        String sentence = inFromUser.readLine();
        sendData = sentence.getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAdress, 4445);
        clientSocket.close();
    }
}

public class UDPServer {

    public static void main(String[] args) throws IOException {
        DatagramSocket serverSocket = new DatagramSocket(4445);
        byte[] receiveData = new byte[1024];
        while(true) {
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            serverSocket.receive(receivePacket);
            String sentence = new String(receivePacket.getData());
            System.out.println("RECEIVED: " + sentence);
        }
    }
}

You forgot to actually send the package over the socket. 您忘记了实际通过套接字发送包裹。

Simply add 只需添加

clientSocket.send(sendPacket);

just before 就在之前

clientSocket.close();

in UDPClient.main() and everything will work. UDPClient.main() ,一切正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM