繁体   English   中英

使用套接字在Java中发送事件

[英]using sockets to send events in java

我有一个用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");

如您所见,此套接字服务器能够识别事件{'error', 'end', 'data'}并且我可以定义更多信息!

我的问题是,如何用Java将事件发送给它?


这是我在这里在线找到的简单TCP客户端:

 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"); } } } 


在这段代码中,我将如何更改它以便发送诸如{'error', 'end', 'data'}

我相信您可以使用skt.getOutputStream()write()获得输出流,以便节点服务器获取数据。 仅在以其他某种方式丢失/干扰连接时才会发生该错误。

暂无
暂无

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

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