简体   繁体   English

如何在Java套接字中创建用于接收数据的侦听器

[英]How to create a listener for receiving data in Java socket

I need to send and receive data between a client and a server. 我需要在客户端和服务器之间发送和接收数据。 The server will be managing multiple clients at once, so it needs to be able to send and receive data with little latency. 该服务器将一次管理多个客户端,因此它需要能够以很少的延迟发送和接收数据。

At the moment I can both send and receive data from the client to the server but it is done procedural, so if any data is lost the server will freeze until the client sends new data. 目前,我既可以从客户端向服务器发送数据,也可以从服务器接收数据,但是这是过程性的,因此,如果丢失任何数据,服务器将冻结,直到客户端发送新数据。 The issue is that if the server is returning data then both the server and client will freeze, waiting for data from the other. 问题是,如果服务器正在返回数据,则服务器和客户端都将冻结,并等待对方的数据。

My current methods to receive and send data 我目前的接收和发送数据的方法

    public void run(){
        while(true){
            byte[] data = new byte[1024]; 
            DatagramPacket packet = new DatagramPacket(data, data.length);
            try {
                socket.receive(packet);
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("SERVER > " +new String(packet.getData()));
        }
    }

    public void sendData(byte[] data){
        DatagramPacket packet = new DatagramPacket(data, data.length, 6969);
        try {
            socket.send(packet);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Ideally I would like something like ActionListener that can let me get an action whenever data is received. 理想情况下,我希望像ActionListener这样的东西可以让我在收到数据时立即执行任何操作。 At the moment it will run a couple of ticks every time it receives data. 目前,每次接收数据时,它将运行几次滴答声。

This is where the use of threads comes in. I'm not a big on java when it comes to coding but I think this will help you. 这就是使用线程的地方。在编码方面,我对Java的了解不大,但是我认为这对您有帮助。 This is the server side code 这是服务器端代码

public static void main(String[] args) throws IOException {
    ServerSocket s = new ServerSocket(8000);
    while(true) {
        Socket socket = s.accept();
        HandleClient c = new HandleClient(socket);
        Thread t = new Thread(c);
        t.start();
    }

}

HandleClient code HandleClient代码

public class HandleClient implements Runnable{
Socket socket;

HandleClient(Socket socket){
    this.socket = socket;
}

public void run() {
    try{
        DataInputStream inputFromClient = new DataInputStream(socket.getInputStream());
        DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());

        double radius;  

        while(true){
            radius = inputFromClient.readDouble();
            double area = radius * radius * Math.PI;
            outputToClient.writeDouble(area);
        }
    }catch(Exception e) {}
}
}

And client side 和客户端

public static void main(String[] args){
    try{

        //System.out.println(add);
        Socket socket = new Socket("localhost",8000);
        Scanner input = new Scanner(System.in);
        DataInputStream inputFromServer = new DataInputStream(socket.getInputStream());
        DataOutputStream outputToServer = new DataOutputStream(socket.getOutputStream());
        double radius;
        System.out.println("Client running at IP address: "+socket.getLocalAddress().toString() +"and port number: "+socket.getLocalPort());


        System.out.println("Enter the value of radius");
        radius = input.nextDouble();

        System.out.println("Writing input");
        outputToServer.writeDouble(radius);
        System.out.println(inputFromServer.readDouble());
    }catch (Exception E){}
}

It's not the same as what you are working on but it's just a template to use threads to handle requests coming from clients. 它与您正在处理的内容不同,而只是使用线程处理来自客户端的请求的模板。 You can modify this to make your project work. 您可以修改它以使您的项目正常工作。

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

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