Object located in the main thread is not initialized by another thread - java

I put together a class of an client app that should connect to a socket and it should automatically retrieve a DefaultTreeModel from the server or a simple String object as a test. The issue is that inside the main RemoteNetworking class the DefaultTreeModel or the String are successfully received but if I try to get them using getClientTreeModel() or verifiFromOutside i'm getting only null objects. Can you please help me understand this behavior? I'll place the code bellow.
package Networking;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
public class RemoteNetworking extends Thread{
private volatile Socket remoteSocket;
private volatile boolean isRunning = true;
private Thread currentThread;
private volatile ObjectOutputStream oos;
private volatile ObjectInputStream ois;
private volatile DefaultTreeModel treeModel = null;
private String IP;
private int port;
private static volatile String test;
public RemoteNetworking(String IP, int port) {
this.IP = IP;
this.port = port;
}
public void connect() {
try {
SocketAddress socketAddress = new InetSocketAddress(IP, port);
remoteSocket = new Socket();
remoteSocket.connect(socketAddress);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private synchronized void setReceivedTreeModel(DefaultTreeModel receivedTreeModel) {
this.treeModel = receivedTreeModel;
}
public synchronized void disconnect() {
try {
//oos.writeObject("Disconnect");
oos.flush();
//oos.close();
isRunning = false;
remoteSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized DefaultTreeModel getClientTreeModel() {
return treeModel;
}
public synchronized void verifyFromOutside() {
System.out.println(test);
}
#Override
public void run() {
connect();
synchronized(this) {
this.currentThread = Thread.currentThread();
}
try {
ois = new ObjectInputStream(remoteSocket.getInputStream());
oos = new ObjectOutputStream(remoteSocket.getOutputStream());
oos.writeObject("DataTree");
oos.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(isRunning) {
try {
Object object = (Object)ois.readObject();
/*if(object instanceof DefaultTreeModel) {
//this received object is not null
setReceivedTreeModel((DefaultTreeModel)object);
if(treeModel==null) {
System.out.println("Null object in RemoteNetworking");
}
verifyFromOutside();
}*/
if(object instanceof String) {
this.test = (String)object;
System.out.println(test);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Related

Multi-Client Server request Handler

I need to implement a Server in java that accepts connections from clients (no limit) then the clients make requests to the server and the server should respond to the request, but just to the client who made the request. I dont know how to start with this...
I can make it work 1 to 1 connection, and I know How to make a multi-client chat in which the server respond to everyone, but how can I, from the server, select the client to respond, just to that which made the request??
package negocio;
import java.io.*;
import java.net.*;
//import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Servidor {
private ServerSocket servidor;
private Socket cliente;
private OutputStream os;
private ObjectInputStream ois;
private InputStream is;
private DataInputStream leerS;
private DataOutputStream escribirS;
private ObjectOutputStream oos;
public Servidor(){
try {
servidor = new ServerSocket(5000);
System.out.println("creador serv");
cliente = new Socket();
cliente = servidor.accept();
System.out.println("cliente conec");
} catch (IOException e) {
e.printStackTrace();
}
}
public String recibirString(){
String mens = "";
try {
leerS = new DataInputStream(cliente.getInputStream());
mens = "Mensaje del cliente: "+leerS.readUTF();
} catch (IOException ex) {
Logger.getLogger(Servidor.class.getName()).log(Level.SEVERE, null, ex);
}
return mens;
}
public Object recibirObjeto(){
System.out.println("Recibiendo");
try {
ois = new ObjectInputStream(cliente.getInputStream());
return ois.readObject();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("llego nullo");
return null;
}
}
public void enviarObjeto(Object obj){
try {
oos = new ObjectOutputStream(cliente.getOutputStream());
oos.writeObject(obj);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

OSGI bundle and threads

I am new in OSGI and i have current aim. I have 10 threads, it's writing their names in a file. After recording thread sleep random 0..1 sec. This all must be a bundle. I create it, but i'm not sure Is this correct. Can any comments?
package helloworld;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import writer.StartThreads;
public class Activator implements BundleActivator {
public void start(BundleContext context) throws Exception {
System.out.println("Start Thred!!");
new StartThreads().Execute();
}
public void stop(BundleContext context) throws Exception {
System.out.println("Goodbye World!!");
}
}
1
package writer;
import writer.WriterLogs;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class StartThreads {
public static void Execute() {
BufferedWriter writer = null;
File textFile = new File("threadLog.txt");
// if file doesnt exists, then create it
if (!textFile.exists()) {
try {
textFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
writer = new BufferedWriter(new FileWriter(textFile, true));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < 10; i++) {
WriterLogs wrt = new WriterLogs(writer);
Thread worker = new Thread(wrt);
worker.setName("Nisha-" + i);
worker.start();
try {
worker.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2
package writer;
import java.io.BufferedWriter;
import java.io.IOException;
public class WriterLogs implements Runnable {
private BufferedWriter writer;
public WriterLogs(BufferedWriter wr) {
this.writer = wr;
}
#Override
public void run() {
try
{
try {
synchronized(this.writer) {
this.writer.write(Thread.currentThread().getName() + "\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// set random 0...1 s.
Thread.sleep((long)(Math.random() * 1000));
System.out.println(Thread.currentThread().getName());
}
catch (InterruptedException interruptedException)
{
/*Interrupted exception will be thrown when a sleeping or waiting
* thread is interrupted.
*/
System.out.println( Thread.currentThread().getName() +interruptedException);
}
}
}
This is not correct. Like Boris the Spider states, when your bundle stops, you should free any resources and stop any processing the bundle was doing. So from the stop method you should somehow signal your threads to stop as soon as they can.
In practice you might get away with letting the code run, but this is definitely not how you should write your code in OSGi (which is what you're asking).

How to print message from a server to the textclient?

I want to print message from a server.For example:I am User1 and I am chatting with user User2.
I want to see this(in the text client console):
User1:Hello
User2:Hi!How are you?
I can see the messages I sent but only in the Server console.Here is my code(to show message in console in text client class):
EDIT:I have put all the classes that I modified.I didn't put the exceptions classes,ServerConfig and Message and PrivateMessage.ServerConfig return port 9000 and max clients 100,the method getAll() from message returns the message+sender.
import java.net.*;
import java.io.*;
public class ClientPeer extends Thread{
String _username;
Socket _Socket;
public ClientPeer(String _username, Socket _Socket)
{
this._username = _username;
this._Socket = _Socket;
}
public void run()
{
try{
ObjectInputStream _objin=new ObjectInputStream(_Socket.getInputStream());
Message _messfromserver=(Message)_objin.readObject();
System.out.println(_messfromserver.getAll());
}catch(IOException e){e.printStackTrace();}
catch(ClassNotFoundException e){e.printStackTrace();}
}
public void sendMessage(String _message) throws IOException {
ObjectOutputStream _obj = new ObjectOutputStream(
_Socket.getOutputStream());
_obj.writeObject(new Message(_username, _message));
_obj.flush();
}
public void sendMessage(String _message, String _receiver)
throws IOException {
ObjectOutputStream _obj = new ObjectOutputStream(
_Socket.getOutputStream());
_obj.writeObject(new PrivateMessage(_username, _message, _receiver));
_obj.flush();
}
}
Server :
import java.io.*;
import java.net.*;
import java.util.*;
public class Server {
static ServerConfig _svconfig = new ServerConfig();
// final static int _mysocket;
public static void main(String[] args) {
try {
final int _mysocket = _svconfig.getPORTNumber();
ServerSocket _serversocket = new ServerSocket(_mysocket);
Socket _clientsocket = _serversocket.accept();
ServerPeer _serverpeer = new ServerPeer(_clientsocket);
_serverpeer.methodCall();
_serversocket.close();
}
catch (MissingKeyException e) {
e.printStackTrace();
} catch (UnknownKeyException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (ConnectException e) {
e.printStackTrace();
} catch (BindException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (SocketException e) {
System.out.println("You have been disconnected");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
TextClient:
import java.io.*;
import java.net.*;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class TextClient {
public TextClient() {
}
public static void main(String[] args) throws IOException,
UnknownHostException, ConnectException,InterruptedException {
Socket _socket = new Socket("localhost", 9000);
System.out.println("Please enter your desired username:");
Scanner _new = new Scanner(System.in);
String _inputname = _new.nextLine();
System.out.println("Success.You can now type your messages!");
ClientPeer _clientpeer = new ClientPeer(_inputname, _socket);
Scanner _scan = new Scanner(System.in);
String _input = _scan.nextLine();
_clientpeer.start();
while (true) {
if (!_input.equals("exit")) {
if (_input.startsWith("/w"))
_clientpeer.sendMessage(_input, "username");
else
_clientpeer.sendMessage(_input);
} else
break;
_input = _scan.nextLine();
}
}
}
ServerPeer:
import java.net.*;
import java.io.*;
public class ServerPeer {
Socket _socket;
public ServerPeer(Socket _socket) {
this._socket = _socket;
}
public void methodCall() throws IOException, UnknownHostException,
ClassNotFoundException {
ObjectInputStream _ois = new ObjectInputStream(_socket.getInputStream());
Message _message;
while (_socket.isConnected()) {
_message = (Message) _ois.readObject();
System.out.print( _message.getAll());
_ois = new ObjectInputStream(_socket.getInputStream());
}
}
}
The question is really unspecified. If you want to see it on the client console just initiate the console on the client-side and print out the messages. Can you tell more about the problem? Where you need help?

KnockKnockServer in Java

I am newbie in java networking ,I am trying to make a server application in java called instant messaging without GUI. So whenever i run the program it says
" Main method not found in class Methods, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application" -ECLIPSE
Please help me what's wrong in my code.
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
// FIRST FILE //
public class main{
public static void main (String[] args) {
Server s=new Server();
s.runningserver();
}
}
//SECOND FILE//
public class Server {
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
//wait For Connection,then display connection information
private void waitforConnection() {
System.out.println("wait for Someone to Connect.....\n");
try {
connection=server.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("error In Acceptance of Server!!\n...");
}
System.out.println(("Connection Established"+connection.getInetAddress().getHostName()));
}
//Setting Up Streams to Get Input and Output
private void setupStreams(){
try {
output=new ObjectOutputStream(connection.getOutputStream());
output.flush();
input=new ObjectInputStream(connection.getInputStream());
System.out.println("Your Streams are Perfectly Working...");
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println("Error Found! in Streaming Connectionos");
e.printStackTrace();
}
}
// While Chatting Method....!!//
private void whileChatting() throws IOException{
String Message="You are now Connected!!\n";
sendMessage(Message);
//abletoType(true);
do{
try{
Message=(String) input.readObject();
System.out.println("\n"+Message);
}
catch(ClassNotFoundException e ){
System.out.println("wtf---Fuck\n YOu\n Bloody\n HAcker!!!\n");
}
}
while(!Message.equals("CLIENT--END"));
}
// Closing All Streams and Socket after you are done//
private void closeCrap(){
System.out.println("\nClosing Connection...........Bye Bye\n");
//abletoType(false);
try {
output.close();
input.close();
connection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Couldn't Close Connections!");
}
}
//Sending Messages to Client
private void sendMessage(String message){
try {
output.writeObject("SERVER--- "+message);
output.flush();
System.out.println("\nServer- "+message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Dude I cant Send yeaah..");
}
}
// Setting up the Server
public void runningserver(){
try {
server=new ServerSocket(4444,100);
while(true){try{
//connect and Have connection
waitforConnection();
setupStreams();
whileChatting();
}
finally{
closeCrap();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
EDIT: Here is the solution and I checked it and for me it works (run the MainClass.java file!):
//MainClass.java file:
public class MainClass {
public static void main (String[] args) {
Server s=new Server();
s.runningserver();
}
}
//Server.java file:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
// wait For Connection,then display connection information
private void waitforConnection() {
System.out.println("wait for Someone to Connect.....\n");
try {
connection = server.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("error In Acceptance of Server!!\n...");
}
System.out.println(("Connection Established" + connection
.getInetAddress().getHostName()));
}
// Setting Up Streams to Get Input and Output
private void setupStreams() {
try {
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
System.out.println("Your Streams are Perfectly Working...");
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println("Error Found! in Streaming Connectionos");
e.printStackTrace();
}
}
// While Chatting Method....!!//
private void whileChatting() throws IOException {
String Message = "You are now Connected!!\n";
sendMessage(Message);
// abletoType(true);
do {
try {
Message = (String) input.readObject();
System.out.println("\n" + Message);
} catch (ClassNotFoundException e) {
System.out.println("wtf---Fuck\n YOu\n Bloody\n HAcker!!!\n");
}
} while (!Message.equals("CLIENT--END"));
}
// Closing All Streams and Socket after you are done//
private void closeCrap() {
System.out.println("\nClosing Connection...........Bye Bye\n");
// abletoType(false);
try {
output.close();
input.close();
connection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Couldn't Close Connections!");
}
}
// Sending Messages to Client
private void sendMessage(String message) {
try {
output.writeObject("SERVER--- " + message);
output.flush();
System.out.println("\nServer- " + message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Dude I cant Send yeaah..");
}
}
// Setting up the Server
public void runningserver() {
try {
server = new ServerSocket(4444, 100);
while (true) {
try {
// connect and Have connection
waitforConnection();
setupStreams();
whileChatting();
} finally {
closeCrap();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I can run that without an exception.
The Problem is your main method
public static void main (String[] args) {}
Is not in the class where you run it.
//separate file A.java
public class A
{}
//separate file B.java
public class B
{
public static void main (String[] args) {}
}
If you now run B, it works, because B.java has a main method. BUT: if you run A.java it says:
no main methode found. The file you want to run (A, B, etc. must have a main method defined)
If you run a java file, it will look for a main method (start point of execution).
The main method must be a method of the class:
import java.net.Socket;
public class Server {
public static void main (String[] args) {
Server s=new Server();
s.runningserver();
}
So it must come after the class declaration.

Server reply to Client message failing due to closed socket - Java Client-Server example

I'm creating this little client-server program to learn about sockets, and so far, I'm having a bit of trouble. For the purpose of this post, I consolidated the code into a single class. And the code will compile. (So it will show the same errors I get)
When the client connects to the server, the server socket properly creates a socket on the server-side. The Client then successfully sends a message to the server, but when the server tries to send a response to the client, there is an error saying the socket is closed.
Main.java
package main;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Hashtable;
public class Main {
boolean running = true;
public static void main(String[] args){
new Main().start();
}
public void start(){
new Thread(new ConnectionListener()).start(); //Starts Server
try {
connectToServer();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public class ConnectionListener implements Runnable{
public void run() {
ServerSocket ss = null;
try {
ss = new ServerSocket(31415);
}catch (BindException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
}
while(running){
try {
Socket sock = ss.accept();
ServerConnection c = new ServerConnection(sock);
c.start();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void connectToServer() throws UnknownHostException, IOException{
//Create Connection to Server
Socket socket = new Socket("localhost",31415);
ClientConnection cc = new ClientConnection(socket);
cc.start();
//Send First Message to Server
Hashtable<Integer, String> htt = new Hashtable<Integer, String>();
htt.put(0,"Hello, This is a Chat Test");
Message m = new Message(Message.Type.CHAT,htt);
cc.sendMessage(m);
}
public class ServerConnection{
Socket sock;
boolean connected = true;
public ServerConnection(Socket sock){
this.sock = sock;
}
public void start() {
new Thread(new RequestListener()).start();
}
private void handleMessage(Message m){
System.out.println("Server : Handle message " + m.type.toString());
}
public void disconnect(){
System.out.println("Disconnect user");
}
public void sendMessage(Message m){
try {
ObjectOutputStream os = new ObjectOutputStream(sock.getOutputStream());
os.writeObject(m);
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class RequestListener implements Runnable{
public void run() {
ObjectInputStream is = null;
try {
is = new ObjectInputStream(sock.getInputStream());
while(connected){
try {
Message m = (Message)
is.readObject(); //EOFException
handleMessage(m);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch(SocketException e){
disconnect();
e.printStackTrace();
break;
}catch (IOException e) {
//e.printStackTrace(); //EOFException Here
}
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public class ClientConnection {
private Socket socket;
private boolean connected = true;
public ClientConnection(Socket socket) {
this.socket = socket;
}
public void start(){
new Thread(new RequestListener()).start();
}
public void sendMessage(Message m){
try {
ObjectOutputStream os = new ObjectOutputStream(socket.getOutputStream());
os.writeObject(m);
os.flush();
os.close();
} catch (IOException e) {
System.out.println("Error Sending Message");
e.printStackTrace();
}
}
public void close() throws IOException{
Message m = new Message(Message.Type.DISCONNECT,null);
sendMessage(m);
socket.close();
}
private void handleMessage(Message m){
System.out.println("Client : Handle message " + m.type.toString());
}
class RequestListener implements Runnable{
public void run() {
ObjectInputStream is = null;
try {
System.out.println(socket.isConnected()); //true
System.out.println(socket.isClosed()); //false
InputStream iss = socket.getInputStream();
is = new ObjectInputStream(iss); //socketClosedException
while(connected){
try {
Message m = (Message)is.readObject();
handleMessage(m);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch(SocketException e){
System.out.println("Server Disconnected");
break;
}catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
Message.java
package main;
import java.io.Serializable;
import java.util.Hashtable;
public class Message implements Serializable{
public enum Type{
LOGIN, PM, DISCONNECT, INCORRECT_LP,CORRECT_LP, UPDATE_USERLIST, CHAT, INCORRECT_VERSION
}
public Type type;
Hashtable ht;
public Message(Type type, Hashtable ht){
this.type = type;
this.ht = ht;
}
public Object get(Object o){
return ht.get(o);
}
}
There's nothing 'random' about it.
Closing the input or output stream of a Socket closes the other stream and the Socket.
In this case you are closing the ObjectOutputStream you have wrapped around the socket's output stream, which closes that output stream, which closes the socket's input stream and the socket.

Categories