SMS Receiving using JSMPP sometimes stop - java

I am using JSMPP from Google to receive SMS messages from SMS Service Centre. Sometimes, my program stops receiving SMS from SMSC, I have to close the program and Re-Open the program. Then Queued SMSes from SMSC starts receive. This happens after some time, like after 7 or 8 hours. Here is the code I'v used
SMPP Init Code
l.info("SMPP Initialization");
SMPPSession s = new SMPPSession();
s.setMessageReceiverListener(new Receive(s));
s.connectAndBind(Settings.smsc_host,Settings.smsc_port, BindType.BIND_TRX,
Settings.smsc_user, Settings.smsc_password,Settings.smsc_msg_setting, TypeOfNumber.UNKNOWN,
NumberingPlanIndicator.UNKNOWN, null, Settings.smsc_timeout);
ProcessSMS.s = s;
l.info("SMPP Initialization Success");
SMS Receive Code
package sms;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.log4j.Logger;
import org.jsmpp.bean.AlertNotification;
import org.jsmpp.bean.DataSm;
import org.jsmpp.bean.DeliverSm;
import org.jsmpp.bean.MessageType;
import org.jsmpp.extra.ProcessRequestException;
import org.jsmpp.session.DataSmResult;
import org.jsmpp.session.MessageReceiverListener;
import org.jsmpp.session.Session;
import processor.ProcessSMS;
public class Receive implements MessageReceiverListener {
private static final ExecutorService pool = Executors.newFixedThreadPool(10);
private static final Logger l = Logger.getLogger(Receive.class);
private Thread thread;
public Receive(){
super();
}
public Receive(Session s){
this();
}
#Override
public DataSmResult onAcceptDataSm(DataSm arg0, Session arg1)
throws ProcessRequestException {
return null;
}
#Override
public void onAcceptAlertNotification(AlertNotification arg0) {
}
#Override
public void onAcceptDeliverSm(DeliverSm arg0)
throws ProcessRequestException {
l.info("Received SMS " + arg0);
if(MessageType.SMSC_DEL_RECEIPT.containedIn(arg0.getEsmClass())){
}else{
pool.submit(new ProcessSMS(arg0));
//thread = new Thread(new ProcessSMS(arg0));
//thread.start();
}
}
}
And here is the state change class
package sms;
import java.io.IOException;
import global.Shared;
import log.SMSCStateLogger;
import org.jsmpp.bean.BindType;
import org.jsmpp.bean.NumberingPlanIndicator;
import org.jsmpp.bean.TypeOfNumber;
import org.jsmpp.extra.SessionState;
import org.jsmpp.session.SMPPSession;
import org.jsmpp.session.Session;
import org.jsmpp.session.SessionStateListener;
import processor.ProcessSMS;
import settings.Settings;
public class StateChange implements SessionStateListener{
private static SMSCStateLogger l = new SMSCStateLogger(StateChange.class);
private Session s;
#Override
public void onStateChange(SessionState arg0, SessionState arg1, Object arg2) {
//arg0 = new State
//arg1 = old State
if(!arg0.isBound() && arg1.isBound()){
int con = Shared.getNextReConnectInterval();
l.info("State changed from " + arg1 + " to " + arg0 + " on " + arg2);
while(true){
l.info("Re Connection in " + con + " ms");
try{
Thread.sleep(con);
}catch(InterruptedException iex){
l.fatal("Re Connection failed due to exception " + iex);
break;
}
s = new SMPPSession();
((SMPPSession) s).setMessageReceiverListener(new Receive(s));
s.addSessionStateListener(new StateChange());
try{
((SMPPSession) s).connectAndBind(Settings.smsc_host,Settings.smsc_port, BindType.BIND_TRX,
Settings.smsc_user, Settings.smsc_password,Settings.smsc_msg_setting, TypeOfNumber.UNKNOWN,
NumberingPlanIndicator.UNKNOWN, null, Settings.smsc_timeout);
}catch(IOException ioex){
l.fatal("Connection failed due to " + ioex.getMessage());
}
ProcessSMS.s = (SMPPSession) s;
l.info("Re Connection success");
break;
}
}
}
}
Does anybody have an idea what is going on ?

Updated the JSMPP API from https://github.com/uudashr/jsmpp.
Download the source with git
run mvn install to create the jar archive.

Related

get result from websocket async call in sync call with concurrency classes

In my Spring project I'm using websocket client (org.java_websocket.client.WebSocketClient) It's worked as fine, main problem is in my code I can to get result with onMessage method but it's Asyc and I need result in Sync caller, other websocket clients are similar behavior too
Async is basically working concept in websocket
import java.util.Collections;
import java.util.concurrent.ExecutionException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.extensions.IExtension;
import org.java_websocket.handshake.ServerHandshake;
import org.java_websocket.protocols.IProtocol;
import org.java_websocket.protocols.Protocol;
public class EmptyClient extends WebSocketClient {
private final static Draft_6455 draft = new Draft_6455(Collections.<IExtension>emptyList(), Collections.<IProtocol>singletonList(new Protocol("my-protocol")));
private String request = null, response = null;
public EmptyClient(String serverUri, String request) throws URISyntaxException {
super(new URI(serverUri), draft);
this.request = request;
setConnectionLostTimeout(3000);
connect();
}
#Override
public void onOpen(ServerHandshake handshakedata) {
send(request);
System.out.println("new connection opened");
}
#Override
public void onClose(int code, String reason, boolean remote) {
System.out.println("closed with exit code " + code + " additional info: " + reason + " remote:" + remote);
}
#Override
public void onMessage(String message) {
this.response = message;
close();
}
#Override
public void onMessage(ByteBuffer message) {
System.out.println("received ByteBuffer");
}
#Override
public void onError(Exception ex) {
System.err.println("an error occurred:" + ex);
}
public String getResponse() {
return response;
}
public static void main(String[] args) throws URISyntaxException, ExecutionException, InterruptedException {
String res = new EmptyClient("ws://123.abc:8888/", "{\"command\":\"create\",\"id\":\"1234\"}").getResponse();
System.out.println("response : "+res);
}
}
at the frist I think I could to use Future<T> and ExecutorService but main problem is Future itself is Async and result by onMessage method is Async too
let me to show you how is changed my previous code :
import java.util.Collections;
import java.util.concurrent.ExecutionException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.extensions.IExtension;
import org.java_websocket.handshake.ServerHandshake;
import org.java_websocket.protocols.IProtocol;
import org.java_websocket.protocols.Protocol;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class EmptyClient extends WebSocketClient {
private final static Draft_6455 draft = new Draft_6455(Collections.<IExtension>emptyList(), Collections.<IProtocol>singletonList(new Protocol("my-protocol")));
private String request = null, response = null;
private ExecutorService executor = Executors.newSingleThreadExecutor();
public EmptyClient(String serverUri, String request) throws URISyntaxException {
super(new URI(serverUri), draft);
this.request = request;
setConnectionLostTimeout(3000);
connect();
}
#Override
public void onOpen(ServerHandshake handshakedata) {
send(request);
System.out.println("new connection opened");
}
#Override
public void onClose(int code, String reason, boolean remote) {
System.out.println("closed with exit code " + code + " additional info: " + reason + " remote:" + remote);
executor.shutdown();
}
#Override
public void onMessage(String message) {
this.response = message;
close();
}
#Override
public void onMessage(ByteBuffer message) {
System.out.println("received ByteBuffer");
}
#Override
public void onError(Exception ex) {
System.err.println("an error occurred:" + ex);
}
public Future<String> getResponse() {
return executor.submit(() -> {
return response;
});
}
public static void main(String[] args) throws URISyntaxException, ExecutionException, InterruptedException {
Future<String> res = new EmptyClient("ws://123.abc:8888/", "{\"command\":\"create\",\"id\":\"1234\"}").getResponse();
System.out.println(res.isDone() + res.get());
}
}
I can not to use Future as return type of onMessage method because it's belong to WebSocketClient class that I used
we know by get method from Future class is right way to get result, if any method by Furter was exist that I could to call it in onMessage method when response is exposed then get method returned actual Furtur<String> Object but there is nothing to do, maybe another concurrency class or mixed technique are better to use
hence I call EmptyClient class in sync method and I need that result to produce something else, how can I to resolve it ? maybe other Concurrency API classes and or locker is there to use

SNMP4j with snmpv3 response and error is null

I'm using snmp4j 3.4.2 inside my java application (full code below)
I'm trying to execute a snmpget with snmpv3, security DES and auth MD5 and custom OID (python script, which is executed by snmp's extend funtionality). To create better understanding I used SnmpConstants.sysUpTime in the example below.
The SNMP resource has this user configured:
defSecurityName demo
defSecurityLevel authPriv
defAuthType MD5
defPrivType DES
defAuthPassphrase pass
defPrivPassphrase pass
I'm already using this user and resource to successfully perform the snmpget with python (pysnmp) and bash (snmpget), so I can definitely tell that my setup works and the java code is the problem.
I have two java classes (Listener.java and ServerStatusHelper.java)
Listener.java contains main and calls the snmpGet inside ServerStatusHelper.java, other code of Listener is excluded as its not neccessary.
import org.snmp4j.PDU;
import org.snmp4j.ScopedPDU;
import org.snmp4j.Snmp;
import org.snmp4j.Target;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.security.AuthMD5;
import org.snmp4j.security.AuthSHA;
import org.snmp4j.security.PrivAES128;
import org.snmp4j.security.PrivDES;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.VariableBinding;
public class Listener {
public static void main(String[] args) {
ServerStatusHelper agent = new ServerStatusHelper("host.tld", "udp", 161, "demo", "demo",
"pass", "pass", new AuthMD5(), new PrivDES(), true);
try {
agent.startAgent();
ResponseEvent response = agent.snmpGetOperation(SnmpConstants.sysUpTime);
if (response != null) {
System.out.println(
"response null - error: "+ response.getError() +
"peerAddress: " + response.getPeerAddress() +
"source: " + response.getSource().toString() +
"request: " + response.getRequest());
}
} catch (
IOException e) {
e.printStackTrace();
}
}
}
ServerStatusHelper.java
import java.io.IOException;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.ScopedPDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.UserTarget;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.security.AuthGeneric;
import org.snmp4j.security.AuthMD5;
import org.snmp4j.security.PrivDES;
import org.snmp4j.security.PrivacyGeneric;
import org.snmp4j.security.SecurityLevel;
import org.snmp4j.security.SecurityModels;
import org.snmp4j.security.SecurityProtocols;
import org.snmp4j.security.USM;
import org.snmp4j.security.UsmUser;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.TransportIpAddress;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultTcpTransportMapping;
import org.snmp4j.transport.DefaultUdpTransportMapping;
public class ServerStatusHelper {
private Address nmsIP;
private String user;
private String securityName;
private String privacyPassword;
private String authorizationPassword;
private AuthGeneric authProtocol;
private PrivacyGeneric privacyProtocol;
private String protocol;
private boolean encryption;
private long timeOut = 1000;
private int noOfRetries = 10;
private Snmp snmp;
private UserTarget target;
private CommunityTarget v1target;
ServerStatusHelper(String ip, String protocol, int snmpPort, String username, String securityName,
String privacyPassword, String authPassowrd, AuthGeneric authProtocol, PrivacyGeneric privacyProtocol,
boolean encryption) {
nmsIP = GenericAddress.parse(protocol + ":" + ip + "/" + snmpPort);
System.out.println("NMS IP set : " + nmsIP.toString());
this.protocol = protocol;
this.user = username;
this.securityName = securityName;
this.privacyPassword = privacyPassword;
this.authorizationPassword = authPassowrd;
this.authProtocol = authProtocol;
this.privacyProtocol = privacyProtocol;
this.encryption = encryption;
SecurityProtocols.getInstance().addAuthenticationProtocol(new AuthMD5());
SecurityProtocols.getInstance().addPrivacyProtocol(new PrivDES());
}
public void startAgent() throws IOException {
if (snmp == null) {
TransportMapping<? extends TransportIpAddress> transport = null;
if (protocol.equalsIgnoreCase("udp")) {
System.out.println("UDP Protocol selected.");
transport = new DefaultUdpTransportMapping();
} else {
System.out.println("TCP Protocol selected.");
transport = new DefaultTcpTransportMapping();
}
snmp = new Snmp(transport);
USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
SecurityModels.getInstance().addSecurityModel(usm);
transport.listen();
snmp.getUSM().addUser(new OctetString(user),
new UsmUser(new OctetString(securityName), authProtocol.getID(),
new OctetString(authorizationPassword), privacyProtocol.getID(),
new OctetString(privacyPassword)));
if (encryption)
target = createUserTarget();
else
v1target = createUserTargetWithoutEncryption();
}
}
public ResponseEvent snmpSetOperation(VariableBinding[] vars) throws IOException {
PDU setPdu = new ScopedPDU();
for (VariableBinding variableBinding : vars) {
setPdu.add(variableBinding);
}
return snmp.send(setPdu, target);
}
public ResponseEvent snmpGetOperation(OID oid) throws IOException {
if (encryption) {
PDU getPdu = new ScopedPDU();
getPdu.add(new VariableBinding(oid));
getPdu.setType(ScopedPDU.GET);
return snmp.get(getPdu, target);
} else {
PDU getPdu = new PDU();
getPdu.add(new VariableBinding(oid));
getPdu.setType(PDU.GET);
return snmp.get(getPdu, v1target);
}
}
private UserTarget createUserTarget() {
UserTarget target = new UserTarget();
target.setAddress(nmsIP);
target.setRetries(noOfRetries);
target.setTimeout(timeOut);
target.setVersion(SnmpConstants.version3);
target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
target.setSecurityName(new OctetString(securityName));
return target;
}
private CommunityTarget createUserTargetWithoutEncryption() {
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString("public"));
target.setAddress(nmsIP);
target.setRetries(noOfRetries);
target.setTimeout(timeOut);
target.setVersion(SnmpConstants.version1);
return target;
}
public long getTimeOut() {
return timeOut;
}
public void setTimeOut(long timeOut) {
this.timeOut = timeOut;
}
public int getNoOfRetries() {
return noOfRetries;
}
public void setNoOfRetries(int noOfRetries) {
this.noOfRetries = noOfRetries;
}
}
The execution of the program exits with
NMS IP set : **IPREMOVED**/161
UDP Protocol selected.
response null - error: nullpeerAddress: **IPREMOVED**/161source: org.snmp4j.Snmp#e580929 request: GET[{contextEngineID=80:00:1f:88:80:5e:2e:49:07:2f:68:44:57:00:00:00:00, contextName=}, requestID=588252045, errorStatus=0, errorIndex=0, VBS[1.3.6.1.2.1.1.3.0 = Null]]
Anyone has an idea what I'm doing wrong?
Edit:
From the servers syslog I can see, that the request arrives at the resource:
Jul 31 11:52:46 loadbalancer snmpd[1219]: Connection from UDP: [IP REMOVED]:54734->[IP REMOVED]:161
Jul 31 11:52:46 loadbalancer snmpd[1219]: Connection from UDP: [IP REMOVED]:54734->[IP REMOVED]:161
#i-shm I think you are doing everything ok.
The only problem in your code could be just the line in which you evaluate the response variable. Your are indicating response != null when it should be actually response == null. I mean:
import org.snmp4j.PDU;
import org.snmp4j.ScopedPDU;
import org.snmp4j.Snmp;
import org.snmp4j.Target;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.security.AuthMD5;
import org.snmp4j.security.AuthSHA;
import org.snmp4j.security.PrivAES128;
import org.snmp4j.security.PrivDES;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.VariableBinding;
public class Listener {
public static void main(String[] args) {
ServerStatusHelper agent = new ServerStatusHelper("host.tld", "udp", 161, "demo", "demo",
"pass", "pass", new AuthMD5(), new PrivDES(), true);
try {
agent.startAgent();
ResponseEvent event = agent.snmpGetOperation(SnmpConstants.sysUpTime);
final PDU response = event.getResponse();
if (response == null) {
System.out.println(
"response null - error: "+ event.getError() +
"peerAddress: " + event.getPeerAddress() +
"source: " + event.getSource().toString() +
"request: " + event.getRequest());
} else {
System.out.println("Response PDU:" + response.toString());
// Process the response as you need, maybe something like this:
long sysUpTime = response.get(0).getVariable().toLong();
// You can find relevant information in the javadocs of the library:
// https://agentpp.com/doc/snmp4j/index.html?org/snmp4j/package-summary.html
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is why you do not receive errors in the java code and your syslog indicates that the requests were actually sent.

Modded Command in Minecraft 1.8.9 command doesn't exist in Multiplayer server

I am developing some minecraft mod for 1.8.9.
What I'm trying to create is command that simply send message to sender.
here's the code for command class and main class
command class:
package happyandjust.happymod.commands;
import java.util.HashMap;
import java.util.List;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.EnumChatFormatting;
public class Command extends CommandBase {
private HashMap<String, String> collection = new HashMap<String, String>();
#Override
public String getCommandName() {
return "collection";
}
#Override
public String getCommandUsage(ICommandSender sender) {
return "collection <enchant name>";
}
#Override
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
collection.put("harvesting", "Wheat Collection Level 2");
collection.put("cubism", "Pumpkin Collection Level 5");
if (args.length < 1) {
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "Usage: /collection [Enchant Name]"));
return;
}
if (args.length == 1) {
String enchant_name = args[0].toLowerCase();
String collec = collection.get(enchant_name);
if (collec == null) {
sender.addChatMessage(new ChatComponentText(
EnumChatFormatting.RED + enchant_name.toUpperCase() + " is not valid Enchant Name"));
return;
}
sender.addChatMessage(new ChatComponentText(
EnumChatFormatting.GREEN + enchant_name.toUpperCase() + " is at " + collection.get(enchant_name)));
}
}
#Override
public boolean canCommandSenderUseCommand(ICommandSender sender) {
return true;
}
}
main class:
package happyandjust.happymod.main;
import happyandjust.happymod.commands.Command;
import happyandjust.happymod.proxy.CommonProxy;
import happyandjust.happymod.util.Reference;
import net.minecraftforge.client.ClientCommandHandler;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
#Mod(modid = Reference.MOD_ID, name = Reference.NAME, version = Reference.VERSION)
public class HappyMod {
#Instance
public static HappyMod instance;
#SidedProxy(clientSide = Reference.CLIENT_PROXY_CLASS, serverSide = Reference.COMMON_PROXY_CLASS)
public static CommonProxy proxy;
#EventHandler
public static void preInit(FMLPostInitializationEvent e) {
}
#EventHandler
public static void init(FMLInitializationEvent e) {
ClientCommandHandler.instance.registerCommand(new Command());
}
#EventHandler
public static void postInit(FMLPostInitializationEvent e) {
}
}
It works fine in single player but if I went to the multi player server like hypixel.
It says "Unknown command"
I have no idea to do this
Can anyone help me to work this command in multi player server?
You need to override the getRequiredPermissionLevel() method from CommandBase for it to work on multiplayer.
#Override
public int getRequiredPermissionLevel() {
return 0;
}

Custom Java Socket class

This is my first time messing around with Sockets, and it was working up until now. Basically, I have a custom ServerSocket class named Server and a custom Socket class named Client.
When Client tries to connect to Server, Server performs a little check to make sure it is actually Client that it trying to make the connection, and not some other socket, because Client has certain methods that I need.
However, this check always returns false. Here is my Server connection code:
package me.eli.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import me.eli.client.Client;
public class Server extends ServerSocket {
private final Map<Client, IOPair> clients = new HashMap<Client, IOPair>();
public Server(final int port) throws IOException {
super(port);
System.out.println("Server started on " + getLocalPort() + "... Waiting for client!");
}
public Client waitOnClient() throws IOException {
final Socket generalClient = accept();
final Client client;
if(!(generalClient instanceof Client)) {
client = null;
PrintWriter out = new PrintWriter(generalClient.getOutputStream(), true);
out.println("Access denied: " + generalClient.getClass().getSimpleName());
log("Invalid client: " + generalClient.getClass().getName() + " (" + generalClient.getInetAddress().getHostAddress() + ")");
out.close();
} else
client = (Client) generalClient;
if(client == null)
return null;
client.setServer(this);
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
broadcast(client.getName() + " has joined.");
clients.put(client, new IOPair(in, out));
System.out.println("Client (" + client.getName() + ") connected from " + client.getInetAddress().getHostAddress());
out.println("Connected! Welcome to the server.");
return client;
}
#Override
public void close() throws IOException {
for(Client c : getClients())
kick(c, "Server closed");
super.close();
}
public void kick(Client c, String reason) {
try {
c.message("disconnect", reason);
c.close();
} catch(IOException e) {
log("Failed to kick " + c.getName() + ": " + e.getMessage());
c.message("error", "Failed to disconnect");
}
}
public void log(String message) {
getServerOut().println(message);
}
public void log(String source, String message) {
log("<" + source + "> " + message);
}
public void broadcast(String message) {
log("broadcast", message);
for(Client c : getClients())
c.message("broadcast", message);
}
public Client[] getClients() {
return clients.keySet().toArray(new Client[clients.keySet().size()]);
}
public BufferedReader getClientIn(Client c) {
return clients.get(c).getIn();
}
public PrintWriter getClientOut(Client c) {
return clients.get(c).getOut();
}
public InputStream getServerIn() {
return System.in;
}
public PrintStream getServerOut() {
return System.out;
}
public static boolean isServerRunningOn(final int port) {
try {
new ServerSocket(port).close();
return false;
} catch(IOException e) {
return true;
}
}
}
And here is my Client connection code:
package me.eli.client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.Socket;
import me.eli.server.IOPair;
import me.eli.server.Server;
public class Client extends Socket {
private Server server;
private final IOPair serverio;
private final String name;
public Client(final String host, final int port) throws IOException {
this(host, port, "Guest-" + (int) (Math.random() * 10000));
}
public Client(final String host, final int port, final String name) throws IOException {
super(host, port);
System.out.println("Connected to server on " + host + ":" + port);
BufferedReader in = new BufferedReader(new InputStreamReader(getInputStream()));
PrintWriter out = new PrintWriter(getOutputStream(), true);
this.name = name;
this.serverio = new IOPair(in, out);
String input;
if((input = in.readLine()) != null)
System.out.println("<Welcome message> " + input);
out.println("Yay! I'm connected!");
}
#Override
public synchronized void close() throws IOException {
if(serverio != null) {
if(server != null)
server.broadcast(getName() + " has disconnected.");
message("server", "Disconnected.");
super.close();
serverio.getIn().close();
serverio.getOut().close();
} else
super.close();
}
public void message(String source, String message) {
getClientOut().println("<" + source + "> " + message);
}
public String getName() {
return name;
}
public void setServer(Server server) {
this.server = server;
}
public Server getServer() {
return server;
}
public BufferedReader getServerIn() {
return serverio.getIn();
}
public PrintWriter getServerOut() {
return serverio.getOut();
}
public InputStream getClientIn() {
return System.in;
}
public PrintStream getClientOut() {
return System.out;
}
}
I'm not the most experienced with networking, but this confuses me because I do indeed connect with my Client class. Thanks in advance!
Server performs a little check to make sure it is actually Client that it trying to make the connection
Impossible and nonsensical. The Client class is at the other end of the connection. It is not magically transmitted to your accept() method. If you want to validate your client you will have to build something into your application protocol.
Notes:
Calling Client.setServer() is similarly futile. It is not magically transmitted to the client.
It is possible to get your ServerSocket-derived class to create Client objects instead of Socket objects in its accept() method, but that doesn't actually solve the issue you're trying to solve.

CORBA Client stopped or hang without errors

My client stopped working when i use the method that have a class object "bd" below as a parameter although i use listener object successfully. "Marked as bold"
NOte that , when i tried to use another method that have for example any pramater "STring" works successfully.
import java.util.Properties;
import org.omg.CORBA.ORB;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAHelper;
import org.omg.CosNaming.NameComponent;
import org.omg.CosNaming.NamingContext;
import org.omg.CosNaming.NamingContextHelper;
public class BackupDaemonMain {
public static void main(String[] args) {
try {
//initialize orb
Properties props = System.getProperties();
props.put("org.omg.CORBA.ORBInitialPort", "1050");
//Replace MyHost with the name of the host on which you are running the server
props.put("org.omg.CORBA.ORBInitialHost", "localhost");
ORB orb = ORB.init(args, props);
System.out.println("Initialized ORB");
//Instantiate Servant and create reference
POA rootPOA = POAHelper.narrow(
orb.resolve_initial_references("RootPOA"));
MessageListenerImpl listener = new MessageListenerImpl();
BackupDaemonImpl bdImpl=new BackupDaemonImpl();
// bdImpl.backupDaemonUser("Yarab");
rootPOA.activate_object(listener);
rootPOA.activate_object(bdImpl);
MessageListener ref = MessageListenerHelper.narrow(
rootPOA.servant_to_reference(listener));
**BackupDaemon bd = BackupDaemonHelper.narrow(
rootPOA.servant_to_reference(bdImpl));**
System.out.println("After rootPOA.servant_to_reference(bdImpl)); ");
//Resolve MessageServer
MessageServer msgServer = MessageServerHelper.narrow(
orb.string_to_object("corbaname:iiop:1.2#localhost:1050#MessageServer"));
BackupServer bdServer=BackupServerHelper.narrow(
orb.string_to_object("corbaname:iiop:1.2#localhost:1050#BackupServer"));
//Register listener reference (callback object) with MessageServer
/* if(bd==null)
{
System.out.println("Null");
}
else
{
System.out.println("Not Null With " + bd.backupDaemonUser());
}*/
// bd.backupDaemonMacAddress("YYYYYYYYYY");
System.out.println("Initialized ORB +++++++++++++++++++++++ ");
msgServer.register(ref);
**bdServer.registerBackupDaemon(bd);**
System.out.println("Initialized ORB +++++++++++++++++++++++ )))))))))");
//System.out.println("I am Here" +
//bd.deleteBackup("00000000000","asdas");//);
System.out.println("Initialized ORB +++++++++++++++++++++++ _____________________________");
System.out.println("Listener registered with MessageServer With User :- ");
System.out.println("Backup Daemon registered with BackupServer With User :- " );
//Activate rootpoa
rootPOA.the_POAManager().activate();
//Wait for messages
System.out.println("Wait for incoming messages");
orb.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Server implementation is
// BackupServerImpl.java
import java.util.Enumeration;
import java.util.Vector;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;
import org.omg.PortableServer.*;
import org.omg.PortableServer.POA;
import java.util.Properties;
// import util.CORBAAlgorithms;
public class BackupServerImpl extends BackupServerPOA {
private ORB orb;
public void setORB(ORB orb_val){
orb = orb_val;
}
public String sayHello(){
return "\nHello world !!\n";
}
public void shutdown(){
orb.shutdown(false);
}
// This BankServer's list of Banks.
private Vector myBackups;
public BackupServerImpl()
{
//super("In Impl");
System.out.println("\n \t # Constructor of Server");
}
public BackupServerImpl(String name) {
// super(name);
myBackups = new Vector();
}
public boolean registerBackupDaemon(BackupDaemon bd) throws InvalidBackupDaemonException
{
System.out.println("\n \t Backup Agent Registration With User" + bd.backupDaemonUser());
return true;
}
public boolean unRegisterBackupDaemon(String backupDaemonMacAddress) throws
InvalidBackupDaemonException {
System.out.println("Backup Daemon Un-Registration With Mac " + backupDaemonMacAddress);
return true;
}
public BackupDaemon[] getBackupDeamons() {
BackupDaemon[] list = new BackupDaemon[myBackups.size()];
myBackups.copyInto(list);
Enumeration e = myBackups.elements();
while (e.hasMoreElements()) {
((BackupDaemon)e.nextElement())._duplicate();
}
return list;
}
}
You may have missed the NameService in our urls
corbaname:iiop:1.2#localhost:1050/NameService#BackupServer
The call to bdServer could also hang on the remote site...
your run method of org.omg.CORBA.ORB blocks on the current thread. You should have started it in a separate thread. Refer the javadoc . Run your ORB like
Thread orbThread = new Thread("Orb Thread") {
public void run() {
orb.run();
}
};
orbThread.start();

Categories