我有几个客户端连接,一个应该监听其他的数据。如何在它们之间建立桥接(不是数组迭代器)?
示例伪代码:
socket.on('data', function(chunk){
decodeChunk(chunk.toString('hex'), function(response){
if(response.name === 'toDB'){
//write smth. to DB
}
if(response.name === 'readDB'){
//watch all incoming tcp sockets with 'toDB' and continiously
//send to client connected with this socket
}
});
})
我可以使用像RabbitMQ这样的东西,但它不适用于现阶段,以保持开发更灵活。
任何建议表示赞赏。
答案 0 :(得分:0)
使用纯伪代码解决这个问题有点棘手,但无论如何我都会试一试。
如果我理解正确,那么toDB和readDB就是样本数据,并且有多个toDB。这意味着,你也有一堆toXY与相应的readXY或一堆toPQ与相应的readPQ。如果是这样,那么只要连接了toSOMETHING,就可以将该套接字存储在readSOMETHING下。如果密钥已经存在,那么您只需将toSOMETHING套接字附加到它。及时看起来像这样:
var socketData = {
readDB: {
sockets: [
<socket-object-toDB-1>,
<socket-object-toDB-2>,
<socket-object-toDB-3>
]
},
readXY: {
sockets: [
<socket-object-toXY-1>,
<socket-object-toXY-2>,
<socket-object-toXY-3>
]
}
}
然后你的伪代码可能看起来像
socket.on('data', function(chunk){
decodeChunk(chunk.toString('hex'), function(response){
if(response.name === 'toDB'){
//write smth. to DB
if (socketData['readDB']) {
// already exists, simply append incoming socket to it's sockets array
socketData['readDB'].sockets.push(socket);
} else {
// does not exist, add it with a sockets array
socketData['readDB'] = {
sockets: [socket]
}
}
if(response.name === 'readDB'){
// Write to all sockets of readDB
socketData['readDB'].sockets.forEach(function(sock) {
sock.write('Whatever message\r\n');
});
}
});
})
答案 1 :(得分:0)
结束这样的服务:
import javax.swing.*;
import java.awt.event.*;
public class Actions extends JFrame implements ActionListener{
JPanel pnl=new JPanel();
ImageIcon ic1=new ImageIcon("/home/mudit/Downloads/duke.png");
JButton btn1=new JButton("Click",ic1);
JTextArea ta=new JTextArea(5,37);
public static void main(String[]args)
{
Actions gui=new Actions();
}
public Actions()
{
super("Swing Window");
setSize(500,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(pnl);
btn1.setHorizontalTextPosition(JButton.CENTER);
btn1.setVerticalTextPosition(JButton.BOTTOM);
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
pnl.add(btn1);
pnl.add(ta);
btn1.setEnabled(true);
ta.setText("Button is enabled");
btn1.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent event)
{
if(event.getSource()==btn1)
{
ta.setText("Button is Clicked");
}
}
}