Asynchornous SNMP get message with SNMP4J - java

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

Related

Is there a way to connect all ObjectOutputStream's to one Input stream?

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

BufferingResponseListener and getContentAsString append the previously fetched content

I run a custom WebSocketServlet for Jetty, which sends short text push notifications (for an async mobile and desktop word game) to many platforms (Facebook, Vk.com, Mail.ru, Ok.ru also Firebase and Amazon messaging) using a Jetty HttpClient instance:
public class MyServlet extends WebSocketServlet {
private final SslContextFactory mSslFactory = new SslContextFactory();
private final HttpClient mHttpClient = new HttpClient(mSslFactory);
#Override
public void init() throws ServletException {
super.init();
try {
mHttpClient.start();
} catch (Exception ex) {
throw new ServletException(ex);
}
mFcm = new Fcm(mHttpClient); // Firebase
mAdm = new Adm(mHttpClient); // Amazon
mApns = new Apns(mHttpClient); // Apple
mFacebook = new Facebook(mHttpClient);
mMailru = new Mailru(mHttpClient);
mOk = new Ok(mHttpClient);
mVk = new Vk(mHttpClient);
}
This has worked very good for the past year, but since I have recently upgraded my WAR-file to use Jetty 9.4.14.v20181114 the trouble has begun -
public class Facebook {
private final static String APP_ID = "XXXXX";
private final static String APP_SECRET = "XXXXX";
private final static String MESSAGE_URL = "https://graph.facebook.com/%s/notifications?" +
// the app access token is: "app id | app secret"
"access_token=%s%%7C%s" +
"&template=%s";
private final HttpClient mHttpClient;
public Facebook(HttpClient httpClient) {
mHttpClient = httpClient;
}
private final BufferingResponseListener mMessageListener = new BufferingResponseListener() {
#Override
public void onComplete(Result result) {
if (!result.isSucceeded()) {
LOG.warn("facebook failure: {}", result.getFailure());
return;
}
try {
// THE jsonStr SUDDENLY CONTAINS PREVIOUS CONTENT!
String jsonStr = getContentAsString(StandardCharsets.UTF_8);
LOG.info("facebook success: {}", jsonStr);
} catch (Exception ex) {
LOG.warn("facebook exception: ", ex);
}
}
};
public void postMessage(int uid, String sid, String body) {
String url = String.format(MESSAGE_URL, sid, APP_ID, APP_SECRET, UrlEncoded.encodeString(body));
mHttpClient.POST(url).send(mMessageListener);
}
}
Suddenly the getContentAsString method called for successful HttpClient invocations started to deliver the strings, which were fetched previously - prepended to the the actual result string.
What could it be please, is it some changed BufferingResponseListener behaviour or maybe some non-obvious Java quirk?
BufferingResponseListener was never intended to be reusable across requests.
Just allocate a new BufferingResponseListener for every request/response.

how to receive source IP address from multiple snmp traps with snmp4j

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.

Why does netty dont send my own POJO over network?

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

Sending a class instance through a static reference member in a small chat client

I am building a small chat-room app in Java.
What I am trying to do here is to send the current class ClientGUI instance (this) through a static ClientGUI reference member. The ServerApplication class is supposed to receive this current clientGUI reference through a regular static getter (done in ServerApplication.main).
After some tiresome debugging I still can't figure out how come the Server side reference remains null after receiving the ClientGUI ref (The getCurrentClientGuiReference() fails).
(Of course - the sent ref is initialized before it is being transferred to server side).
Is it not possible to transfer the current ref through a local static ref member?
Perhaps I missed a something?
Bellow is the relevant code.
Thanks in advance.
Client side:
package chatApplication;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import javax.swing.*;
public class ClientGUI implements StringConsumer, StringProducer
{
//Graphic components
private JFrame frame;
private JButton btConnect,btSend;
private JTextField tfText, tfServerName, tfPort, tfNickName;
private JPanel north,south,center;
ActionListener listener;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
JLabel mainLable = new JLabel();
//Utilities and connection components
private ConnectionProxy consumer = null;
private ConnectionProxy producer = null;
private ClientDescriptor clientDescriptor = null;
//Connection creation switch
private boolean isConnection = false;
//Client details meant for ClientDescriptor
static private String nickname = "Noname";
static private String serverAddress = "127.0.0.1";
static private String port = "1300";
static private ClientGUI currentClientGuiReference = null;
public ClientGUI()
{
frame = new JFrame("Chit & Chat");
listener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == btConnect)
{
if (isConnection == false)
{
ClientGUI.nickname = tfNickName.getText();
ClientGUI.serverAddress = tfServerName.getText();
ClientGUI.port = tfPort.getText();
ClientGUI.currentClientGuiReference = ClientGUI.this;
clientDescriptor = new ClientDescriptor(nickname, serverAddress, port, currentClientGuiReference); // Identical though NOT related to serverapplication's clientdescriptor
consumer = new ConnectionProxy(clientDescriptor, ClientGUI.this);
//Connecting client consumer as a producer
ClientGUI.this.addConsumer(consumer);
//Temporary text
mainLable.setText("Client consumer/producer thread is connected and running!");
}
}
if (event.getSource() == btSend)
{
String outGoingMessageToChat = tfText.getText();
producer.consume(outGoingMessageToChat); //sending outgoing msg to prducer.consume --> writeutf
}
}
};
btConnect = new JButton ("Connect to chat");
btSend = new JButton ("Send Message");
btConnect.addActionListener(listener);
btSend.addActionListener(listener);
tfText = new JTextField(50);
tfPort = new JTextField(10);
tfServerName = new JTextField(20);
tfNickName = new JTextField(10);
tfServerName.setText("127.0.0.1");
tfPort.setText("1300");
tfNickName.setText("Nickname");
north = new JPanel();
south = new JPanel();
center = new JPanel();
north.setBackground(Color.blue);
south.setBackground(Color.gray);
center.setBackground(Color.white);
south.add(tfText);
south.add(btSend);
north.add(tfNickName,BorderLayout.WEST);
north.add(tfServerName);
north.add(tfPort);
north.add(btConnect,BorderLayout.WEST);
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing (WindowEvent event)
{
ClientGUI.this.removeConsumer(clientDescriptor);
frame.setVisible(false);
frame.dispose();
System.exit(0);
}
}
);
frame.add(north,BorderLayout.NORTH);
frame.add(center,BorderLayout.CENTER);
frame.add(south,BorderLayout.SOUTH);
}
public void go()
{
ClientGUI.currentClientGuiReference = ClientGUI.this;
frame.setSize(700,700);
frame.setVisible(true);
mainLable.setText("Hey! " +
"Please enter a nickname, Server Address and a port in the text fields above" +
" and press 'Connect to chat'");
center.add(mainLable);
frame.add(center, BorderLayout.WEST);
if (isConnection == true)
{
mainLable.setText("Your details were sent.");
}
}
#Override
public void addConsumer(StringConsumer consumer)
{
this.producer = (ConnectionProxy)consumer;
//All actions completed - client thread producer/consumer is running.
isConnection = true;
}
#Override
public void removeConsumer(StringConsumer sc)
{
consumer.removeConsumer(clientDescriptor);
}
#Override
public void consume(String inComingMessageFromChat)
{
//Temporary code
mainLable.setText(inComingMessageFromChat);
}
public ConnectionProxy getConsumer()
{
return consumer;
}
public void setConsumer(ConnectionProxy consumer)
{
this.consumer = consumer;
}
/**
* #param args
*/
public static void main(String[] args)
{
ClientGUI clientGUI = new ClientGUI();
clientGUI.go();
}
public static String getNickname() {return nickname;}
public static String getServerAddress() {return serverAddress;}
public static String getPort() {return port;}
public static ClientGUI getCurrentClientGuiReference() {return currentClientGuiReference;}
}
Server side:
package chatApplication;
import java.net.*;
import java.io.*;
public class ServerApplication {
public static int port = 1300;
public static int backlog = 5;
/**
* #param args
*/
public static void main(String[] args)
{
//Server side network variables
ServerSocket serverSocket = null;
//MessageBoard object
MessageBoard messageBoard = new MessageBoard();
//Client side network variables
Socket clientSocket = null;
ClientDescriptor clientDescriptor = null;
ConnectionProxy clientConnectionProxy = null;
//Client details meant for ClientDescriptor
String clientNickname = "Noname";
String clientServerAddress = "127.0.0.1";
String clientPort = "1300";
ClientGUI clientCurrentGuiReference = null;
try //Creating Server
{
serverSocket = new ServerSocket(port,backlog); //ServerSocket(int port, int backlog)
}
catch(IOException e)
{
e.printStackTrace();
}
while (true)
{
try
{
System.out.println("Server is waiting for Client requests...");
clientSocket = serverSocket.accept(); // A new thread is created for the new client
System.out.println("Client connection request accepted, creating client connection proxy...");
clientConnectionProxy = new ConnectionProxy(clientSocket); //connecting client socket to server
clientConnectionProxy.addConsumer(messageBoard); //Applying specific server system network utilities and connecting proxy to the messageboard
System.out.println("Requesting Client details from Client side...");
clientNickname = ClientGUI.getNickname();
clientServerAddress = ClientGUI.getServerAddress();
clientPort = ClientGUI.getPort();
clientCurrentGuiReference = ClientGUI.getCurrentClientGuiReference();
System.out.println("Creating Client Descriptor...");
clientDescriptor = new ClientDescriptor(clientNickname, clientServerAddress, clientPort, clientCurrentGuiReference);
clientDescriptor.addConsumer(messageBoard);
messageBoard.addConsumer(clientDescriptor);
clientConnectionProxy.start();//Start client connection's thread running
System.out.println("Client thread started...");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
I think static doesn't do what you think it does. If Client and Server are running separately--as in two different processes and two different JVMs--then no amount of assigning any variable to anything will make the same value/object visible to both Client and Server. You'll have to use some way of communicating between the processes.
Once you manage to get a ClientGUI to the Server, I doubt you'll be able to use it the way you want. The ClientGUI is also just an object with no ability to communicate between the Client and Server. You'll have to manage that yourself, too.
The server and client are in different processes, as far as I can see. They're completely separate - setting a static variable in the client process won't change the same static variable in the server process.
The only way I can think of that might work for what you are trying to do is using Serialization that can be used to represent an object as a sequence of bytes and then that can be sent using ObjectOutputStream and received by using ObjectInputStream as they are required in sending/receiving Object.
Although I have worked on a similar project, i didn't require doing something like this.

Categories

Resources