简体   繁体   中英

using sockets to send events in java

I have a simple socket-server written in node.js:

var net = require("net");

var clients = [];

net.createServer(function(socket){

    //Identify this client
    socket.name = socket.remoteAddress + ":" + socket.remotePort;

    //Put this new client in the list
    clients.push(socket);

    //Send welcome message
    socket.write("Welcome " + socket.name + "\n");
    broadcast(socket.name + " joined the room \n");

    //Handle incoming messages from clients
    socket.on('data', function(data){
       broadcast(socket.name + "> " + data, socket);
    });


    //Remove client when it leaves
    socket.on('end', function(){
        clients.splice(clients.indexOf(socket), 1);
        broadcast(socket.name + " left the chat.\n");
    });

    socket.on('error', function(err){
       console.log(err);
    });

    function broadcast(message, sender){
        clients.forEach(function(client){
           if(client === sender) return;
            client.write(message);
        });
        console.log(message);
    }
}).listen(5000);

console.log("Chat server running at port 5000\n");

Here as you can see, this socket server is able to recognize events {'error', 'end', 'data'} and I could define more if I wanted to!

My question is, how do I send events to it in Java?


Here is a simple TCP-Client I found online here :

 import java.lang.*; import java.io.*; import java.net.*; class Client { public static void main(String args[]) { try { Socket skt = new Socket("localhost", 1234); BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream())); System.out.print("Received string: '"); while (!in.ready()) {} System.out.println(in.readLine()); // Read one line and output it System.out.print("'\\n"); in.close(); } catch(Exception e) { System.out.print("Whoops! It didn't work!\\n"); } } } 


In this code, how would I change it so that I can send events such as {'error', 'end', 'data'}

I believe you can obtain the output stream with skt.getOutputStream() and write() to that in order for the node server to get the data. The error only occurs when the connection is lost/disturbed in some other way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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