java RMI Chat - remote server doesn't execute code - java

My chat works fine on the localhost but when I try to do it on the remote server, it doesn't go on.
RemoteClass >
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface ChatInterface extends Remote {
public String getName() throws RemoteException;
public void sendMsg(String message) throws RemoteException;
public void setInterface (ChatInterface x) throws RemoteException; }
ClientImpl >
import Interface.ChatInterface;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class ChatClient extends UnicastRemoteObject implements ChatInterface{
private String name;
private ChatInterface server;
public ChatClient(String name) throws RemoteException{
this.name = name;
}
#Override
public String getName() throws RemoteException {
return this.name;
}
#Override
public void sendMsg(String message) throws RemoteException {
System.out.println(message);
}
#Override
public void setInterface(ChatInterface server) throws RemoteException {
this.server = server;
} }
ClientMain >
import Interface.ChatInterface;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Scanner;
public class Client{
public static void main(String[] args){
if (System.getSecurityManager() == null) {
System.setSecurityManager(new SecurityManager());
}
try {
Registry registry = LocateRegistry.getRegistry("hostname", port);
ChatInterface chatClient = new ChatClient("User01");
ChatInterface chatServer = (ChatInterface) registry.lookup("ChatServer");
System.out.println("[System] Chat is ready");
chatServer.setInterface(chatClient);
String message = "["+chatClient.getName()+"] got connected";
chatServer.sendMsg(message);
Scanner s = new Scanner(System.in);
while (true) {
message = s.nextLine().trim();
message = "["+ chatClient.getName()+"]" + message;
chatServer.sendMsg(message);
}
} catch (Exception e) {
System.out.println("[System] Server failed: " + e);
System.exit(1);
}
} }
ServerImpl >
import Interface.ChatInterface;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
public class ChatServer extends UnicastRemoteObject implements ChatInterface{
private String name;
private ArrayList<ChatInterface> clients;
public ChatServer(String name)throws RemoteException{
this.name = name;
this.clients = new ArrayList<>();
}
#Override
public String getName() throws RemoteException {
return this.name;
}
#Override
public void sendMsg(String message) throws RemoteException {
broadcast(message);
}
#Override
public synchronized void setInterface(ChatInterface client) throws RemoteException {
clients.add(client);
}
public ArrayList<ChatInterface> getClients(){
return clients;
}
private void broadcast(String message) throws RemoteException {
for (ChatInterface client : clients) {
client.sendMsg(message);
}
} }
ServerMain >
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Server {
public static void main(String[] args) {
try {
LocateRegistry.createRegistry(9876);
Registry registry = LocateRegistry.getRegistry(port);
ChatServer chatServer = new ChatServer("Server");
registry.bind("ChatServer", chatServer);
System.out.println("Server ready :)");
} catch (Exception e) {
System.out.println("[System] Server failed: " + e.toString());
System.exit(1);
}
}
}
The server doesn't do anything at this line
chatServer.setInterface(chatClient);
But doesn't provoke any error. It continues to run for both client & server.
If you have any advice, thank you

Related

how to make multi-clients server chat app with java rmi

i made chat room using java rmi but the problem is that the message appears only to one client(the last to connect) for example 3 clients connect to the server(client1,client2,client3)
if client3 sends a message it appears only in server's console . and if server sends a message it appears only to client3's console.
i want to make the message to be shown to all the users connected to the server.
here is my code( i used eclipse for this project):
serveur.java
import java.rmi.*;
import java.rmi.server.*;
import java.util.*;
import java.rmi.registry.*;
public class serveur {
public static void main (String[] argv) {
try {
Scanner s = new Scanner(System.in);
System.out.println("Entrez votre nom et appuyez sur Entree:");
String name=s.nextLine().trim();
chat server = new chat(name);
Registry registre = LocateRegistry.createRegistry(1099);
Naming.rebind( "CHAT",server);
System.out.println(" Le CHAT est pret:");
while(true){
String msg = s.nextLine().trim();
if (server.getClient() != null){
chatint Client = server.getClient();
msg = server.getName()+" : "+msg;
Client.send(msg);
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
client.java
public class client {
public static void main(String args[]) {
try {
Scanner s = new Scanner(in);
out.println("Entrez votre nom et appuyez sur Entrez:");
String name = s.nextLine().trim();
chatint client = new chat(name);
chatint server = (chatint)Naming.lookup("CHAT");
String msg = "["+client.getName()+"] s'est connecte";
server.send(msg);
out.println("[System] Le CHAT est pret:");
server.setClient(client);
while(true){
msg = s.nextLine().trim();
msg = client.getName()+" : "+msg;
server.send(msg);
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
chatint.java
import java.rmi.*;
public interface chatint extends Remote{
public String getName() throws RemoteException;
public void send(String s) throws RemoteException;
public void setClient( chatint c) throws RemoteException;
public chatint getClient() throws RemoteException;
}
chat.java
package projetSid;
import java.rmi.*;
import java.rmi.server.*;
public class chat extends UnicastRemoteObject implements chatint {
public String name;
public chatint client = null;
public chat(String n) throws RemoteException {
this.name = n;
}
public String getName() throws RemoteException {
return this.name;
}
public void setClient(chatint c){
client = c;
}
public chatint getClient(){
return client;
}
public void send(String s) throws RemoteException{
System.out.println(s);
}
}

Java RMI issue: Can't solve Exception in thread "main" java.rmi.NotBoundException: Server

I am getting the following error:
Exception in thread "main" java.rmi.NotBoundException: Server
at java.rmi/sun.rmi.registry.RegistryImpl.lookup(RegistryImpl.java:234)
at java.rmi/sun.rmi.registry.RegistryImpl_Skel.dispatch(RegistryImpl_Skel.java:133)
at java.rmi/sun.rmi.server.UnicastServerRef.oldDispatch(UnicastServerRef.java:468)
at java.rmi/sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:298)
at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:200)
at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:197)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at java.rmi/sun.rmi.transport.Transport.serviceCall(Transport.java:196)
at java.rmi/sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:562)
at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:796)
at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:677)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:676)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
at java.rmi/sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:303)
at java.rmi/sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:279)
at java.rmi/sun.rmi.server.UnicastRef.invoke(UnicastRef.java:380)
at java.rmi/sun.rmi.registry.RegistryImpl_Stub.lookup(RegistryImpl_Stub.java:123)
at client.RMIClient.startClient(RMIClient.java:17)
at client.FahrradClient.main(FahrradClient.java:12)
Can anybody look at my code and tell me where I went wrong? I'd be more than grateful. Would even send a small tip or something lmao I am that desperate.
package server;
import shared.RMI_Interface;
import java.io.IOException;
import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class FahrradServer {
public static void main(String[] args) throws IOException, AlreadyBoundException {
RMI_Interface server = new ConfigImpl();
Registry registry = LocateRegistry.createRegistry(1099);
Runtime.getRuntime().exec("rmiregistry 1099");
registry.bind("Server", server);
System.out.println("Server started");
}
}
package client;
import shared.Fahrrad;
import shared.RMI_Interface;
import java.rmi.*;
import java.rmi.registry.*;
public class RMIClient {
private RMI_Interface server;
public RMIClient() {}
public void startClient() throws RemoteException, NotBoundException {
Registry registry = LocateRegistry.getRegistry("localhost", 1099);
server = (RMI_Interface)registry.lookup("Server");
}
public Fahrrad configureFahrrad(String lenkertyp, String material, String schaltung, String griff ) {
Fahrrad result = null;
try {
result = server.configureFahrrad(lenkertyp, material, schaltung, griff);
} catch (RemoteException e) {
e.printStackTrace();
throw new RuntimeException("Could not contact server");
}
return result;
}
}
package server;
import shared.Fahrrad;
import shared.RMI_Interface;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class ConfigImpl implements RMI_Interface {
public void ConfigImpl() throws RemoteException {
UnicastRemoteObject.exportObject(this, 0);
}
#Override
public Fahrrad configureFahrrad(String lenkertyp, String material, String schaltung, String griff ) throws RemoteException {
Fahrrad f = new Fahrrad();
f.setLenkertyp(lenkertyp);
f.setGriff(griff);
f.setMaterial(material);
f.setSchaltung(schaltung);
if (!lenkertyp.equals( "Faltbarlenker") && !lenkertyp.equals( "Rennradlenker") && !lenkertyp.equals( "Bullhornlenker")) {
throw new IllegalArgumentException("Ungültiger Lenktypinput");
}
if (!material.equals( "Aluminium") && !material.equals( "Stahl") && !material.equals( "Kunststoff")){
throw new IllegalArgumentException("Ungültiges Material!");
}
if (!schaltung.equals("Kettenschaltung") && !schaltung.equals( "Tretlagerschaltung") && !lenkertyp.equals( "Nebenschaltung")) {
throw new IllegalArgumentException("Ungültige Schaltung!");
}
if (!griff.equals( "Kunststoffgriff") && !griff.equals( "Ledergriff") && !lenkertyp.equals( "Schaumstoffgriff")) {
throw new IllegalArgumentException("Ungültige Schaltung!");
}
if (lenkertyp.equals("Faltbarlenker") || lenkertyp.equals("Rennradlenker")) {
if (!material.equals( "Aluminium") && !material.equals( "Kunststoff")) {
throw new IllegalArgumentException(lenkertyp + " kann nur aus Aluminium oder Kunststoff bestehen.");
}
}
if (material.equals("Stahl")) {
if (!schaltung.equals("Kettenschaltung")) {
throw new IllegalArgumentException("Materialtyp "+ material + " kann nur Kettenschaltung haben!");
}
}
if (material.equals("Kunststoff")) {
if (griff.equals("Kunststoffgriff")) {
throw new IllegalArgumentException("Nur Kunststoffmaterial kann Kunststoffgriff haben!");
}
}
if (lenkertyp.equals( "Bullhornlenker") || lenkertyp.equals("Faltbarlenker")) {
if (griff.equals("Ledergriff")) {
throw new IllegalArgumentException("Nur Rennladlenker können Ledergriffe haben!");
}
}
return f;
}
}
package server;
import shared.RMI_Interface;
import java.io.IOException;
import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class FahrradServer{
public static void main(String[] args) throws IOException, AlreadyBoundException {
RMI_Interface server = new ConfigImpl();
Registry registry = LocateRegistry.createRegistry(1099);
Runtime.getRuntime().exec("rmiregistry 1099");
registry.bind("Server", server);
System.out.println("Server started");
}
}
package shared;
public class Fahrrad {
public String lenkertyp;
public String material;
public String schaltung;
public String griff;
public void setLenkertyp(String lenkertyp){
this.lenkertyp=lenkertyp;
}
public String getLenkertyp() {
return lenkertyp;
}
public void setMaterial(String material){
this.material=material;
}
public String getMaterial() {
return material;
}
public void setSchaltung(String schaltung) {
this.schaltung=schaltung;
}
public String getSchaltung() {
return schaltung;
}
public void setGriff(String griff){
this.griff=griff;
}
public String getGriff() {
return griff;
}
}
package shared;
import java.rmi.Remote;
import java.rmi.RemoteException;
// Creating Remote interface for our application
public interface RMI_Interface extends Remote {
public Fahrrad configureFahrrad(String lenkertyp, String material, String schaltung, String griff ) throws RemoteException;
}
I know the code isn't perfect. I will change it but the most important thing is to get the client and server run independently. My client sadly doesn't run.
The steps to follow when creating a RMI application.
Create the "remote" interface.
Your interface RMI_Interface is OK. Nothing to do here.
Create a class that implements the remote interface.
I made the constructor empty. (The rest of the code is unchanged.)
public ConfigImpl() throws RemoteException {
// Empty.
}
Create a RMI server. Here I made a few changes.
package server;
import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import shared.RMI_Interface;
public class FahrradServer {
public static void main(String[] args) {
try {
ConfigImpl server = new ConfigImpl();
RMI_Interface stub = (RMI_Interface) UnicastRemoteObject.exportObject(server, 0);
Registry registry = LocateRegistry.createRegistry(1099);
registry.bind("Server", stub);
System.out.println("Server started");
}
catch (AlreadyBoundException | RemoteException x) {
x.printStackTrace();
}
}
}
Note that calling method createRegistry() will launch the rmiregistry so no need for this line of your code:
Runtime.getRuntime().exec("rmiregistry 1099");
Run the server, i.e. java server.FahrradServer
(I assume you know the correct command that you need to actually launch your server.)
Note that the server program will run forever – unless you kill it.
Write the client. The client will run in a separate JVM so the client needs a main() method so that you can launch it via the java command.
package client;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import shared.Fahrrad;
import shared.RMI_Interface;
public class RMIClient {
private RMI_Interface server;
public void startClient() throws RemoteException, NotBoundException {
Registry registry = LocateRegistry.getRegistry(1099);
server = (RMI_Interface) registry.lookup("Server");
}
public Fahrrad configureFahrrad(String lenkertyp,
String material,
String schaltung,
String griff) throws RemoteException {
return server.configureFahrrad(lenkertyp, material, schaltung, griff);
}
public static void main(String[] args) {
RMIClient client = new RMIClient();
try {
client.startClient();
Fahrrad f = client.configureFahrrad("Faltbarlenker",
"Aluminium",
"Kettenschaltung",
"Kunststoffgriff");
System.out.println("Fahrrad: " + f);
}
catch (RemoteException | NotBoundException x) {
x.printStackTrace();
}
}
}
Since the return value of the remote interface method is a class that you wrote, that class must implement interface Serializable, i.e.
public class Fahrrad implements java.io.Serializable
Now you can launch your RMI client, e.g. java client.RMIClient
Refer to the RMI trail of Oracle's java tutorials.

Blockchain Websocket in Java

I am creating a program in java for websocket for blockchain.
My this example is working well :
`
import java.io.;
import com.neovisionaries.ws.client.;
public class Test
{
private static final String SERVER = "wss://ws.blockchain.info/inv";
public static void main(String[] args) throws Exception
{
WebSocket ws = connect();
ws.sendText("{\"op\":\"unconfirmed_sub\"}");
}
private static WebSocket connect() throws IOException, WebSocketException
{
return new WebSocketFactory().setConnectionTimeout(500000000).createSocket(SERVER)
.addListener(new WebSocketAdapter() {
public void onTextMessage(WebSocket websocket, String message) {
System.out.println(message);
}
})
.connect();
}
} `
but not this one :
`
import java.io.*;
import com.neovisionaries.ws.client.*;
public class Test
{
private static final String SERVER = "wss://ws.blockchain.info/inv";
public static void main(String[] args) throws Exception
{
WebSocket ws = connect();
ws.sendText("{\"op\":\"addr_sub\", \"addr\":\"65SQr6sh9SeS39PRbw8PHGp9wpv39\"}");
}
private static WebSocket connect() throws IOException, WebSocketException
{
return new WebSocketFactory().setConnectionTimeout(500000000).createSocket(SERVER)
.addListener(new WebSocketAdapter() {
public void onTextMessage(WebSocket websocket, String message) {
System.out.println(message);
}
})
.connect();
}
}`
Same way in jquery it is working, but not in java

RMI client com.sun.proxy.Proxy cannot be cast error

Server:
package server;
import java.rmi.*;
public interface iCSServer extends Remote
{
public int Findnumber(int num) throws RemoteException;
}
package server;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;
And
public class CSServer extends UnicastRemoteObject implements iCSServer {
private static final long serialVersionUID = 01; // version 01
int N=1000; // number of ids
int[] Ids=new int[N]; // data structure for storing the Ids
public CSServer() throws RemoteException
{
}
public void Add_Ids() // add ids to data
{
for(int i=0;i<N;i++)
{
Ids[i]=i+ (i+1)*10;
}
}
public int Findnumber(int num) throws RemoteException
{
for(int i=0;i<N;i++)
{
if(num==Ids[i])
{
return i;
}
}
return -1;
}
public static void main(String[] args) throws RemoteException {
System.setProperty("java.rmi.server.hostname","127.0.0.1");
LocateRegistry.createRegistry(1099);
// System.out.println(LocateRegistry.getRegistry(1099).toString());
CSServer obj=new CSServer();
obj.Add_Ids();
try {
Naming.rebind ("CSServer", obj);
System.out.println ("CS218 Server is running.");
}
catch (Exception e) {
System.out.println ("CS218 server cannot run: " + e);
}
}
}
Server starts and runs fine.
Client:
package client;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.*;
public interface iCSServer extends Remote
{
public int Findnumber(int num) throws RemoteException;
}
And
package client;
import java.rmi.Naming;
import java.rmi.registry.*;
public class clientApp {
public static void main(String[] args)
{
try{
iCSServer obj = (iCSServer) Naming.lookup("//localhost:1099/CSServer");
//Registry registry = LocateRegistry.getRegistry("127.0.0.1");
//iCSServer obj=(iCSServer) registry.lookup("CSServer");
System.out.println("pass");
System.out.println(obj.Findnumber(100));
}
catch(Exception ex)
{
System.out.println("fail");
System.out.println(ex.getMessage());
}
}
}
However, when I run the client I get this error:
fail
error unmarshalling return; nested exception is:
java.lang.ClassNotFoundException: server.iCSServer (no security manager: RMI class loader disabled)
then I added a jar'd version of server.ICSServer, I believe that fixed that issue. However, I ran it again and now I get this error:
fail
com.sun.proxy.$Proxy0 cannot be cast to client.iCSServer
Any ideas on how to fix?
You have renamed the interface by putting it into a different package. It has to be the same.

Apache MINA reading from IoSession

I am new to Apache MINA kindly guide me how to read from IoSession. I have stored a POJO in it.
public static EchoUDPServerDiscoveryObjectResponseProperties echoProperties
session.write(echoProperties);
Custom Client:
package client;
import java.net.InetSocketAddress;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.util.logging.Level;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.future.ReadFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.example.udp.client.MemMonClient;
import org.apache.mina.transport.socket.nio.NioDatagramConnector;
/**
*
* #author az
*/
public class CustomClient extends IoHandlerAdapter{
private IoSession session;
private IoConnector connector;
private ConnectFuture connFuture;
public CustomClient() throws InterruptedException{
connector = new NioDatagramConnector();
connector.setHandler(this);
connFuture = connector.connect(new InetSocketAddress("192.168.3.22",6502));
connFuture.addListener(new IoFutureListener<ConnectFuture>() {
public void operationComplete(ConnectFuture future) {
if (future.isConnected()) {
session = future.getSession();
try {
try {
sendData();
// connFuture.await();
} catch (CharacterCodingException ex) {
java.util.logging.Logger.getLogger(MemMonClient.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
private void sendData() throws InterruptedException, CharacterCodingException {
IoBuffer buffer = IoBuffer.allocate(8);
buffer.setAutoExpand(true);
buffer.putString("any", Charset.forName("UTF-8").newEncoder());
buffer.flip();
session.write(buffer);
}
#Override
public void exceptionCaught(IoSession session, Throwable cause)
throws Exception {
cause.printStackTrace();
}
#Override
public void messageReceived(IoSession session, Object message)
throws Exception {
connFuture.getSession().getConfig().setUseReadOperation(true);
ReadFuture r = connFuture.getSession().read();
connFuture.await();
connFuture.getSession().getConfig().setUseReadOperation(true);
Object obj = r.getMessage();
System.out.println("r.getMessage(); "+obj);
IoBuffer buffer = IoBuffer.allocate(2048);
buffer.setAutoExpand(true);
Object objReceived = buffer.getObject();
System.out.println(objReceived.toString());
System.out.println("reveived Session recv...");
}
#Override
public void messageSent(IoSession session, Object message) throws Exception {
System.out.println("Message sent...");
}
#Override
public void sessionClosed(IoSession session) throws Exception {
System.out.println("Session closed...");
}
#Override
public void sessionCreated(IoSession session) throws Exception {
System.out.println("Session created...");
}
#Override
public void sessionIdle(IoSession session, IdleStatus status)
throws Exception {
System.out.println("Session idle...");
}
#Override
public void sessionOpened(IoSession session) throws Exception {
System.out.println("Session opened...");
}
public static void main (String are[]){
try{
new CustomClient();
}catch(Exception ex){ex.printStackTrace();}
}
}
POJO Java
package pojo;
import java.io.Serializable;
/**
*
* #author az
*/
public class kojo implements Serializable{
private String name = "null";
private String address = "null";
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the address
*/
public String getAddress() {
return address;
}
/**
* #param address the address to set
*/
public void setAddress(String address) {
this.address = address;
}
}
Custom Server Java
package server;
import java.io.IOException;
import java.net.InetSocketAddress;
import org.apache.mina.transport.socket.DatagramSessionConfig;
import org.apache.mina.transport.socket.nio.NioDatagramAcceptor;
/**
*
* #author az
*/
public class CustomServer {
public CustomServer(){
try {
NioDatagramAcceptor acceptor = new NioDatagramAcceptor();
acceptor.setHandler(new ServerHandler(this));
//DefaultIoFilterChainBuilder filter = acceptor.getFilterChain();
DatagramSessionConfig dcfg = acceptor.getSessionConfig();
dcfg.setReuseAddress(true);
acceptor.bind(new InetSocketAddress(6501));
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void receiveUpdate(){
}
public static void main(String are[]){
new CustomServer();
}
}
Server Handler
package server;
import java.nio.charset.Charset;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
/**
*
* #author az
*/
public class ServerHandler extends IoHandlerAdapter {
private CustomServer server;
public ServerHandler(CustomServer server) {
this.server = server;
}
#Override
public void messageReceived(IoSession session, Object message)
throws Exception {
if (message instanceof IoBuffer) {
//decode POJO and send to client
IoBuffer buffer = (IoBuffer) message;
System.out.println(buffer.getString(Charset.forName("UTF-8").newDecoder()));
buffer.setAutoExpand(true);
buffer.putObject(new pojo.POJO());
buffer.flip();
session.write(buffer);
System.out.print("Object Attached and Sent");
}
}
#Override
public void messageSent(IoSession session, Object message) {
System.out.println("Message sent");
}
#Override
public void sessionClosed(IoSession session) throws Exception {
System.out.println("Session closed...");
}
#Override
public void sessionCreated(IoSession session) throws Exception {
System.out.println("Session created...");
}
#Override
public void sessionIdle(IoSession session, IdleStatus status)
throws Exception {
System.out.println("Session idle...");
}
#Override
public void sessionOpened(IoSession session) throws Exception {
System.out.println("Session Opened...");
}
}

Categories