i'm using snmp4j to capture trap data from multiple routers,but i don't know how to receive the source IP address from these routers, which router is the sender. That's my code below, maybe it's useful:
public class SNMPTrapReceiver implements CommandResponder {
private MultiThreadedMessageDispatcher dispatcher;
private Snmp snmp = null;
private Address listenAddress;
private ThreadPool threadPool;
private int n = 0;
public SNMPTrapReceiver() {
}
public static void main(String[] args) {
new SNMPTrapReceiver().run();
}
private void run() {
try {
init();
snmp.addCommandResponder(this);
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void init() throws UnknownHostException, IOException {
threadPool = ThreadPool.create("Trap", 10);
dispatcher = new MultiThreadedMessageDispatcher(threadPool,
new MessageDispatcherImpl());
listenAddress = GenericAddress.parse(System.getProperty(
"snmp4j.listenAddress", "udp:0.0.0.0/162"));
TransportMapping<?> transport;
if (listenAddress instanceof UdpAddress) {
transport = new DefaultUdpTransportMapping(
(UdpAddress) listenAddress);
} else {
transport = new DefaultTcpTransportMapping(
(TcpAddress) listenAddress);
}
USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(
MPv3.createLocalEngineID()), 0);
usm.setEngineDiscoveryEnabled(true);
snmp = new Snmp(dispatcher, transport);
snmp.getMessageDispatcher().addMessageProcessingModel(new MPv1());
snmp.getMessageDispatcher().addMessageProcessingModel(new MPv2c());
snmp.getMessageDispatcher().addMessageProcessingModel(new MPv3(usm));
SecurityModels.getInstance().addSecurityModel(usm);
snmp.getUSM().addUser(
new OctetString("MD5DES"),
new UsmUser(new OctetString("MD5DES"), AuthMD5.ID,
new OctetString("UserName"), PrivDES.ID,
new OctetString("PasswordUser")));
snmp.getUSM().addUser(new OctetString("MD5DES"),
new UsmUser(new OctetString("MD5DES"), null, null, null, null));
snmp.listen();
}
public void processPdu(CommandResponderEvent event) {
StringBuffer msg = new StringBuffer();
msg.append(event.toString());
Vector<? extends VariableBinding> varBinds = event.getPDU()
.getVariableBindings();
if (varBinds != null && !varBinds.isEmpty()) {
Iterator<? extends VariableBinding> varIter = varBinds.iterator();
while (varIter.hasNext()) {
VariableBinding var = varIter.next();
msg.append(var.toString()).append(";");
}
}
System.out.println("Message Received: " + msg.toString());
}
}
The CommandResponderEvent contains the sender address in the getPeerAddress() member:
See http://www.snmp4j.org/doc/org/snmp4j/CommandResponderEvent.html#getPeerAddress()
If the trap was forwarded by a proxy, the snmpTrapAddress.0 variable binding (defined in the SNMP-COMMUNITY-MIB, RFC3584) will contain the address of the original trap sender.
Related
I have a Client class and a MessageServer class that communicates to each other via Sockets. And they send Message object to each other(Not implemented yet).
The thing is, in my MesageServer class, i have a implementation like this
LinkedList<Client> clients = new LinkedList<>();
LinkedList<ObjectOutputStream> outs = new LinkedList<>();
LinkedList<ObjectInputStream> ins = new LinkedList<>();
But this approach seems odd and not useful the more i think about it.
I want to get Message objects from 1 output stream, because that way, I don't have to iterate through every OOS object to find out which client actually put an object in the stream.
Am I wrong? How should I approach?
MessageServer
public class MessageServer extends Server implements Runnable{
static LinkedList<Message> messages = new LinkedList<>();
LinkedList<Client> clients = new LinkedList<>();
LinkedList<ObjectOutputStream> outs = new LinkedList<>();
LinkedList<ObjectInputStream> ins = new LinkedList<>();
ExecutorService threads = Executors.newFixedThreadPool(3);
ExecutorService clientThreads = Executors.newCachedThreadPool();
public MessageServer() throws IOException {
super(Vars.MESSAGE_PORT);
}
//Accept the connetions to the server
private class ServerConnection implements Runnable{
#Override
public void run(){
while (true) {
try {
Socket client = serverSocket.accept();
//Read Client data then add to the list
ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream());
ObjectInputStream in = new ObjectInputStream(client.getInputStream());
outs.add(out);
ins.add(in);
Client current = (Client) in.readObject();
if(current.getType()) {
Provider p = (Provider) current;
clients.add(p);
}else{
Receiver r = (Receiver) current;
clients.add(r);
}
} catch (IOException | ClassNotFoundException ex) {
Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
private class ServerIO implements Runnable{
#Override
public void run(){
}
}
public void addToMessages(Message message) {
if (!messages.contains(message)) {
messages.add(message);
}
}
#Override
public void run() {
threads.execute(new ServerConnection());
threads.execute(new ServerIO());
}
}
The Provider and Receiver classes are subclasses of the class Client, they are there for future video stream and act the same way for now.
Message
public class Message implements Serializable {
private final int maxChar = 250;
private String content;
private String timeStamp;
private Client sender;
public Message(Client sender, String content, String timeStamp) {
this.sender = sender;
this.content = content;
this.timeStamp = timeStamp;
}
}
Client
public class Client implements Serializable {
protected String nickname;
protected long id;
protected int key;
/*
* True -> Provider
* False -> Receiver
*/
protected boolean type;
// MessageServer
protected transient ObjectOutputStream msgOut;
protected transient ObjectInputStream msgIn;
protected transient Socket messageSocket;
protected transient Socket videoSocket;
public Client(String nickname, boolean type){
this.type = type;
this.nickname = nickname;
createid();
makeConnection();
key = (int) (Math.random() * 8999) + 1000;
}
void makeConnection(){
try {
messageSocket = new Socket(Vars.IP, Vars.MESSAGE_PORT);
//TODO make connection with videoServer
msgOut = new ObjectOutputStream(messageSocket.getOutputStream());
msgIn = new ObjectInputStream(messageSocket.getInputStream());
msgOut.writeObject(this);
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
I define a schedule task in the main thread, I want to clean the value of the map which caches my project's client information in ChannelHandler. But it doesn't work. What did I do wrong?
This is main app code where I schedule a task.
public class Server {
public static void main(String[] args) throws Exception {
EventLoopGroup boss = new NioEventLoopGroup();
EventLoopGroup work = new NioEventLoopGroup();
final ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1);
ServerBootstrap b = new ServerBootstrap();
//init() code Omitted
ScheduledFuture<?> sf = ctx.executor().scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
HashSet<String> clients = new HashSet<>();
Map<String,String> map = LoginAuthRespHandler.getNodeCheck();
System.out.println(map.size());
for (String key:map.keySet()) {
clients.add(map.get(key));
}
try{
//doSomething();
}catch (Exception e){
e.printStackTrace();
}
map.clear();
clients.clear();
}
},10,10,TimeUnit.SECONDS);
ChannelFuture cf = b.bind(NettyConstant.REMOTEIP,NettyConstant.PORT).sync();
System.out.println("Netty server start ok on: "
+ (NettyConstant.REMOTEIP + " : " + NettyConstant.PORT));
cf.channel().closeFuture().sync();
work.shutdownGracefully();
boss.shutdownGracefully();
}
}
And this is the ChannelHandler code.
public class LoginAuthRespHandler extends ChannelInboundHandlerAdapter {
private static final Logger LOGGER = LoggerFactory.getLogger(LoginAuthRespHandler.class);
private static Map<String, String> nodeCheck = new ConcurrentHashMap<String, String>();
private String[] whiteList = { "127.0.0.1", "192.168.56.1" };
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
AlarmMessage message = (AlarmMessage) msg;
if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_REQ.value()) {
String nodeIndex = ctx.channel().remoteAddress().toString();
AlarmMessage loginResp = null;
if (nodeCheck.containsKey(nodeIndex)) {
loginResp = buildResponse(ResultType.FAIL);
} else {
InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
String ip = address.getAddress().getHostAddress();
boolean isOK = false;
for (String WIP : whiteList) {
if (WIP.equals(ip)) {
isOK = true;
break;
}
}
loginResp = isOK ? buildResponse(ResultType.SUCCESS) : buildResponse(ResultType.FAIL);
if (isOK)
//add a client value to the map
nodeCheck.put(nodeIndex, message.getBody().toString());
}
ctx.writeAndFlush(loginResp);
} else {
ctx.fireChannelRead(msg);
}
}
private AlarmMessage buildResponse(ResultType result) {
AlarmMessage message = new AlarmMessage();
Header header = new Header();
header.setType(MessageType.LOGIN_RESP.value());
message.setHeader(header);
message.setBody(result.value());
return message;
}
#Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
String nodeIndex = ctx.channel().remoteAddress().toString();
ctx.close();
if(nodeCheck.containsKey(nodeIndex)){
nodeCheck.remove(nodeIndex);
}
}
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
//nodeCheck.remove(ctx.channel().remoteAddress().toString());
ctx.close();
ctx.fireExceptionCaught(cause);
}
public synchronized static Map<String, String> getNodeCheck() {
return nodeCheck;
}
}
I have been working in a simple SNMP manager for java using the library SNMP4J. I am trying to send simple asynchronous get messages. I have greated a SNMPmanager to create the PDUs and start the listeners and a simple class named SNMPget that makes a simple get request.
As stated in the javadoc:
Asynchronous responses are returned by calling a callback method on an object instance that implements the ResponseListener interface.
I have followed the exact instructions to implement the callback but looks like the callback method onResponse is never executed when sending a get request. In fact, I have used wireshark to check if packets are being send and the request is correctly send and the correct response is received. Any clue on what I am doing wrong?
public class SNMPManager {
private static SNMPManager instance = new SNMPManager();
private Snmp snmp_ = null;
//Common SNMP variables
private int requestPort = 161;
private int timeout = 10000;
private int retryCount = 1;
private int maxRepetitions = 20;
private int nonRepeaters = 0;
//Singleton pattern
public static SNMPManager getInstance() {
return instance;
}
//Empty Constructor
private SNMPManager() { }
//Start the manager
public void start() throws IOException {
//Create a UDP transport on all interfaces
DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
//Create a SNMP instance
snmp_ = new Snmp(transport);
//Put all the transport mappings into listen mode
snmp_.listen();
}
//Methods for creating targets
// Create the target for version 2c
public Target createVersion2cTarget(String ipaddress, String communityName) {
CommunityTarget target = new CommunityTarget();
target.setAddress(new UdpAddress(String.format("%s/%d", ipaddress, requestPort)));
target.setCommunity(new OctetString(communityName));
target.setTimeout(timeout);
target.setRetries(retryCount);
target.setVersion(SnmpConstants.version2c);
return target;
}
//Methods for creating PDUs
public PDU createGetRequestPdu(String requestOID) {
PDU pdu = new PDU();
//Set the request type
pdu.setType(PDU.GET);
//Set the OID
OID rOID = new OID(requestOID);
pdu.add(new VariableBinding(rOID));
return pdu;
}
//Methods for the request (async mode)
public void getRequest(PDU pdu, Target target, Object userHandle, ResponseListener listener) throws IOException {
snmp_.get(pdu, target, userHandle, listener);
}
}
public class SNMPget {
protected final SNMPManager snmp_;
private String requestOID;
private String ipAddress;
private String communityName;
public SNMPget(String newRequestOID, String hostIpAddress, String newCommunityName) {
snmp_ = SNMPManager.getInstance();
requestOID = newRequestOID;
ipAddress = hostIpAddress;
communityName = newCommunityName;
}
public void get(ResponseListener listener) throws IOException {
Target targetHost = snmp_.createVersion2cTarget(ipAddress, communityName);
PDU pduSNMPget = snmp_.createGetRequestPdu(requestOID);
snmp_.getRequest(pduSNMPget, targetHost, null, listener);
}
}
public class mainTest {
public static void main(String[] args) throws IOException {
SNMPManager snmp = SNMPManager.getInstance();
snmp.start();
ResponseListener listener = new ResponseListener() {
#Override
public void onResponse(ResponseEvent event) {
// Always cancel async request when response has been received
// otherwise a memory leak is created! Not canceling a request
// immediately can be useful when sending a request to a broadcast
// address.
((Snmp) event.getSource()).cancel(event.getRequest(), this);
PDU response = event.getResponse();
System.out.println("Received response "+response);
}
};
SNMPget snmpGetCmd = new SNMPget("1.3.6.1.2.1.1.1.0", "192.168.137.104", "public");
snmpGetCmd.get(listener);
}
}
i try to send the POJO "SecureMessageServerClientMessage" over network to an client. Both are created with the netty-Framework for Async. Socket communications. I am really new to netty, so i take on of the Example code and want to change it, so that it send my POJO over network. I know that is a lot of code but its nearly the sample of them but it dont work .. It would be really nice if some one could tell my why it does not work ..
Here are my classes: Server Main:
public final class SecureChatServer {
static final int PORT = Integer.parseInt(System.getProperty("port", "8992"));
public static void main(String[] args) throws Exception {
SelfSignedCertificate ssc = new SelfSignedCertificate();
SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new SecureChatServerInitializer(sslCtx));
b.bind(PORT).sync().channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
SecureChatServerHandler:
public class SecureChatServerHandler extends SimpleChannelInboundHandler<SecureMessageServerClientMessage> {
static final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
private ArrayList<SecureMessageServerUser> userList = new ArrayList();
#Override
public void channelActive(final ChannelHandlerContext ctx) {
// Once session is secured, send a greeting and register the channel to the global channel
// list so the channel received the messages from others.
ctx.pipeline().get(SslHandler.class).handshakeFuture().addListener(
new GenericFutureListener<Future<Channel>>() {
#Override
public void operationComplete(Future<Channel> future) throws Exception {
channels.add(ctx.channel());
}
});
}
#Override
public void channelRead0(ChannelHandlerContext ctx, SecureMessageServerClientMessage msg ) throws Exception {
System.out.println("Nachricht empfangen!");
System.out.println("Typ: "+msg.getType());
//Send the received message to all channels but the current one.
for (Channel c: channels) {
if (c != ctx.channel()) {
c.writeAndFlush("[" + ctx.channel().remoteAddress() + "] " + msg + '\n');
} else {
c.writeAndFlush("[you] " + msg + '\n');
}
}
}
#Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
Initializer (Server):
public class SecureChatServerInitializer extends ChannelInitializer<SocketChannel> {
private final SslContext sslCtx;
public SecureChatServerInitializer(SslContext sslCtx) {
this.sslCtx = sslCtx;
}
#Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
// Add SSL handler first to encrypt and decrypt everything.
// In this example, we use a bogus certificate in the server side
// and accept any invalid certificates in the client side.
// You will need something more complicated to identify both
// and server in the real world.
pipeline.addLast(sslCtx.newHandler(ch.alloc()));
// On top of the SSL handler, add the text line codec.
pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
pipeline.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
pipeline.addLast(new ObjectEncoder());
// and then business logic.
pipeline.addLast(new SecureChatServerHandler());
}
}
Here is the code of my client:
public final class SecureChatClient {
static final String HOST = System.getProperty("host", "127.0.0.1");
static final int PORT = Integer.parseInt(System.getProperty("port", "8992"));
public static void main(String[] args) throws Exception {
// Configure SSL.
final SslContext sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class).handler(new SecureChatClientInitializer(sslCtx));
// Start the connection attempt.
Channel ch = b.connect(HOST, PORT).sync().channel();
// Read commands from the stdin.
ChannelFuture lastWriteFuture = null;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (;;) {
String line = in.readLine();
if (line == null) {
break;
}
if("send".equals(line)){
System.out.println("Test");
lastWriteFuture = ch.writeAndFlush(new SecureMessageServerClientMessage(1, "test"));
if(lastWriteFuture.isSuccess()){
System.out.println("Success");
}
}
// Sends the received line to the server.
//lastWriteFuture = ch.writeAndFlush(line + "\r\n");
// If user typed the 'bye' command, wait until the server closes
// the connection.
if ("bye".equals(line.toLowerCase())) {
ch.closeFuture().sync();
break;
}
}
// Wait until all messages are flushed before closing the channel.
if (lastWriteFuture != null) {
lastWriteFuture.sync();
}
} finally {
// The connection is closed automatically on shutdown.
group.shutdownGracefully();
}
}
}
And here the handler:
public class SecureChatClientHandler extends SimpleChannelInboundHandler<SecureMessageServerClientMessage> {
#Override
public void channelRead0(ChannelHandlerContext ctx, SecureMessageServerClientMessage msg) throws Exception {
System.err.println(msg);
}
#Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
And at last my POJO:
public class SecureMessageServerClientMessage implements Serializable{
private String message;
private int type;
static final int LISTUSER = 0, MESSAGE = 1, LOGOUT = 2, LOGIN = 3;
private String sender;
private String empfaenger;
private ArrayList<SecureMessageServerUser> userList = new ArrayList();
//Erste MSG, Login am Server
public SecureMessageServerClientMessage(int type, String sender){
this.type=type;
this.sender=sender;
}
//Nur für den Clienten, als Anfrage für die user-List
public SecureMessageServerClientMessage(int type){
this.type=type;
}
//Für MessageTyp 0 - LISTUSER, es wird nur die aktuelle User-Liste übertragen
public SecureMessageServerClientMessage(int type, ArrayList userList){
this.userList=userList;
}
//Für MessageTyp 1 - MESSAGE Es wird der Empfänger, und die Nachricht übertragen
public SecureMessageServerClientMessage(int type, String message, String empfaenger, String sender){
this.type=type;
this.message=message;
this.sender=sender;
this.empfaenger=empfaenger;
}
//Für MessageTyp 1 - Msg, die weitergeleitet werden
public SecureMessageServerClientMessage(int type, String message, String sender){
this.type=type;
this.message=message;
this.sender=sender;
}
public String getMessage(){
return this.message;
}
public int getType(){
return type;
}
public String getSender(){
return this.sender;
}
public ArrayList getList() {
return userList;
}
public ArrayList getUserList() {
return userList;
}
public String getEmpfaenger(){
return this.empfaenger;
}
}
I try to make a chat. When a client send a message to the server, it is working, the server receives the message. So I would like to send this message all the clients. I tried many things but they are not working... Just the client which sends the message, it receives this message
Can You help me please ?
Thanks in advance
PS : Sorry for my bad English
This is the result in the console :
http://i.stack.imgur.com/VS2wf.png
MainClient
public class MainClient {
/**
* #param args the command line arguments
* #throws java.io.IOException
* #throws java.lang.ClassNotFoundException
*/
public static void main(String[] args) throws IOException, ClassNotFoundException {
boolean stop = false;
Socket socket;
Scanner nickScan;
String nick;
socket = new Socket(InetAddress.getLocalHost(), 2009);
System.out.println("Hi, what is your name ?");
nickScan = new Scanner(System.in);
nick = nickScan.nextLine();
User u = new User(nick, false, false, true);
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(u);
EmissionThread e = new EmissionThread(u, socket);
e.start();
while(!stop){
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
Message m = (Message)ois.readObject();
System.out.println(m.getNick() + " : " + m.getMsg());
}
//socket.close();//On ferme les connexions
}
}
MainServer
public class MainServer extends Thread {
public static void main(String[] args) throws InterruptedException, IOException {
// TODO code application logic here
ConnectionThread c = new ConnectionThread();
c.start();
}
}
ConnectionThread
public class ConnectionThread extends Thread {
private static final boolean stop = false;
Socket socketduserveur;
ServerSocket socketserver;
Session s = new Session("#upec");
public ConnectionThread() throws IOException {
this.socketserver = new ServerSocket(2009);
}
public ServerSocket getSocketserver() {
return socketserver;
}
#Override
public void run() {
while (!stop) {
try {
socketduserveur = socketserver.accept(); //On accepte les connexions
ObjectInputStream ois = new ObjectInputStream(socketduserveur.getInputStream());
User u = (User)ois.readObject();
System.out.println(u.getNick() + " c'est connecté");
s.addUserList(u);
if (s.listAlone()) {
System.out.println("Vous etes admin");
u.setAdmin(true);
}
ReceptionThread r = new ReceptionThread(socketduserveur);
r.start();
} catch (ClassNotFoundException ex) {
Logger.getLogger(MainServer.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ConnectionThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
ReceptionThread
public class ReceptionThread extends Thread {
private static final boolean stop = false;
Socket socketduserveur;
ServerSocket socketserver;
public ReceptionThread(Socket socketduserveur) {
this.socketduserveur = socketduserveur;
}
#Override
public void run() {
while (!stop) {
try {
ObjectInputStream ois = new ObjectInputStream(socketduserveur.getInputStream());
Message m = (Message)ois.readObject();
System.out.println(m.getNick() + " : " + m.getMsg());
ObjectOutputStream oos = new ObjectOutputStream(socketduserveur.getOutputStream());
oos.writeObject(m);
} catch (IOException | ClassNotFoundException ex) {
Logger.getLogger(ReceptionThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
EmissionThread
public class EmissionThread extends Thread {
private User u;
private Socket socketduserveur;
private static final boolean stop = false;
public EmissionThread(User u, Socket socketduserveur) {
this.u = u;
this.socketduserveur = socketduserveur;
}
#Override
public void run() {
while (!stop) {
try {
Scanner msgScan;
String msg;
msgScan = new Scanner(System.in);
msg = msgScan.nextLine();
Message m = new Message(u.getNick(), msg);
ObjectOutputStream oos = new ObjectOutputStream(socketduserveur.getOutputStream());
oos.writeObject(m);
} catch (IOException ex) {
Logger.getLogger(EmissionThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Message
public class Message implements Serializable {
private String nick;
private String msg;
public Message(String nick, String msg) {
this.nick = nick;
this.msg = msg;
}
}
Session
public class Session implements Serializable {
private String name;
private ArrayList<String> listSession = new ArrayList();
private ArrayList<User> listUser = new ArrayList();
public Session(String name) {
this.name = name;
}
public void addSession(String name){
listSession.add(name);
}
public void deleteSession(String name){
for(String s : listSession){
if(name.equals(s)){
listSession.remove(s);
}
}
}
public boolean existSession(String name){
for(String s : listSession){
if(name.equals(s)){
return true;
}
}
return false;
}
public void addUserList(User u){
listUser.add(u);
}
public boolean listAlone(){
int compteur = 0;
for(User u : listUser){
compteur++;
}
return compteur == 1;
}
}
User
public class User implements Serializable {
private String nick;
private final Session session;
private boolean admin, moderator, voice;
public User(String nick, boolean admin, boolean moderator, boolean voice) {
this.nick = nick;
this.admin = admin;
this.moderator = moderator;
this.voice = voice;
this.session = new Session("#upec");
}
}
You can use websockets on tomcat for this. If you download tomcat there is a chat app already built as an example