So, i done search for this question..
My directories and files structure looks like (all *.java files have server package):
run2 (shell script)
[server] (folder)
\
\ Server.java
ClientThread.java
ServerConnectionManager.java
.. some other files ...
run2 contains:
find . -name "*.class" -type f -delete
javac -classpath .:server:server/lib/mysqlconn.jar server/Server.java
java -classpath .:server:server/lib/mysqlconn.jar server.Server
As you see, it runs Server. Go look there:
package server;
// imports
public class Server {
public static final int BUFFSIZE = 32;
public static void main (String[] args) throws IOException {
ServerConnectionManager server = new ServerConnectionManager(1234);
server.start();
server.acceptConnections();
server.shutdown();
}
}
Nothing weird in this class, right? Anyway, i think like that.
In this class, as we see, Server create instance of ServerConnectionManager
and call some functions.
Go look at acceptConnections:
public void acceptConnections() {
while(true) {
try {
Socket clientConnection = connection.accept();
ClientThread client = new ClientThread(clientConnection);
/*clients.add(client);
client.start();
System.out.println("[INF] Client connected");
System.out.println("[INF] Summary: " + clients.size() + " clients connected");*/
} catch (IOException e) {
System.out.println("[ERR] Accepting client connection failed");
}
}
}
I commented some lines. I really not need them now.
More about problem:
When i run run2 - server runs and works fine. netstat shows what server wait for connections.
But when i run client, and try connect to server, it shows to me next error:
Exception in thread "main" java.lang.NoClassDefFoundError: server/ClientThread
at server.ServerConnectionManager.acceptConnections(ServerConnectionManager.java:36)
at server.Server.main(Server.java:15)
Caused by: java.lang.ClassNotFoundException: server.ClientThread
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 2 more
I can't understand, why i have this exception ?
Look at directories and files. ClientThread.java exists and placed into server directory and have server package. Compilation doesn't show any error.
What i doing wrong?
There is connection class for client
package client;
// imports
public class ClientConnectionManager {
public Socket connection;
public String host;
public Integer port;
public Boolean connected;
public ClientConnectionManager(String h, Integer p) {
host = h;
port = p;
}
public void connect() {
try {
connection = new Socket(host, port);
} catch (IOException e) {
System.out.println("[INF] Failed connect to server");
}
}
public void disconnect() {
try {
connection.close();
} catch (IOException e) {
System.out.println("[ERR] Connection closing failed");
}
}
}
package server;
// some imports just not removed yet
import java.io.IOException;
import java.net.*;
import java.lang.*;
import java.io.*;
import java.util.*;
import java.sql.*;
class ClientThread extends Thread {
public Socket clientSocket;
public OutputStream out;
public InputStream in;
public Tasks tasks;
public User user;
public ClientThread(Socket socket) {
clientSocket = socket;
try {
out = clientSocket.getOutputStream();
in = clientSocket.getInputStream();
} catch (IOException e) {
System.out.println("Cant initialize I/O in for client socket");
}
}
public void run() {
ServerDatabaseConnectionManager database = new ServerDatabaseConnectionManager();
database.connect();
tasks = new Tasks(database.connection);
user = new User(database.connection);
/** listen for requests from client*/
try {
out.write(new String("_nelo_").getBytes());
} catch (IOException e) {
System.out.println("Cant send auth cmd");
}
ServerInputHandler listen = new ServerInputHandler(this);
listen.start();
}
}
You need to compile ClientThread.java as well
add this before running as well
javac -classpath .:server:server/lib/mysqlconn.jar server/ClientThread.java
This is painful way of managing classpath and compilation, better go for some IDE and build tool (maven)
Server.java does not import ClientThread.java or use ClientThread at all inside the Server class, so your compiler ignores compiling it.
In order to fix this problem, simply include ClientThread.java in the batch you use to compile your project.
javac -classpath .:server:server/lib/mysqlconn.jar server/ClientThread.java
I suggest you look into an IDE though
Related
I am implementing a Client application and a Server application on my Windows computer using two terminals that communicate with each other.
However I cannot get the Client to run. The Server and Java RMI registry run successfully. I have 3 files: Client.java, Server.java and Hello.java
import java.rmi.registry.LocateRegistry; //Client.java
import java.rmi.registry.Registry;
public class Client {
private Client() {}
public static void main(String[] args) {
String host = (args.length < 1) ? null : args[0];
try {
Registry registry = LocateRegistry.getRegistry("127.0.0.1", 1099);
Hello stub = (Hello) registry.lookup("Hello");
String response = stub.sayHello();
System.out.println("response: " + response);
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}
import java.rmi.registry.Registry; //Server.java
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class Server implements Hello {
public Server() {}
public String sayHello() {
return "Hello, world!";
}
public static void main(String args[]) {
try {
Server obj = new Server();
Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);
// Bind the remote object's stub in the registry
Registry registry = LocateRegistry.getRegistry("127.0.0.1", 1099);
registry.bind("Hello", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
import java.rmi.Remote; //Hello.java
import java.rmi.RemoteException;
public interface Hello extends Remote {
String sayHello() throws RemoteException;
}
All three Java files are located in C:\Program Files\Java\jdk1.8.0_321\bin. After compiling them to the same directory, I run the following commands in the command prompt as administrator.
start rmiregistry -J-Djava.class.path=./
Java RMI registry starts successfully in a new command prompt window (no output).
start java Server
Server starts sucessfully in a new command prompt which outputs "Server ready".
java Client
This command is unsuccessful and outputs the following error:
java.net.SocketException: Permission denied: connect
java.rmi.ConnectIOException: Exception creating connection to: 192.168.1.13; nested exception is:
java.net.SocketException: Permission denied: connect
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:635)
at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:131)
at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:235)
at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:180)
at com.sun.proxy.$Proxy0.sayHello(Unknown Source)
at Client.main(Client.java:15)
Caused by: java.net.SocketException: Permission denied: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:75)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:476)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:218)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:200)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:162)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:394)
at java.net.Socket.connect(Socket.java:606)
at java.net.Socket.connect(Socket.java:555)
at java.net.Socket.<init>(Socket.java:451)
at java.net.Socket.<init>(Socket.java:228)
at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40)
at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:148)
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:617)
... 7 more
C:\Program Files\Java\jdk1.8.0_321\bin>_
I am unsure how to get the Client running successfully. I disabled windows firewall and am not using a VPN.
I'm trying to create a client and server application in java. But I receive a "The constructor ServerIO(Socket) is undefined" exception. Can someone tell me what I'm missing here?
My setup.server() function (simplified):
import java.net.Socket;
import java.net.ServerSocket;
import inputOutput.*;
public void server (int port) {
try {
ServerSocket sock = new ServerSocket(port);
Socket client = sock.accept();
ServerIO serverIO = new ServerIO(client);
} catch (IOException e) {
e.printStackTrace();
}
}
My input output handler constructor (simplified):
import java.net.Socket;
public ServerIO(Socket socket) {
this.socket = socket;
try {
this.in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
} catch (IOException e){
e.printStackTrace();
}
}
Stack trace:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The constructor ServerIO(Socket) is undefined
at Setup.server(Setup.java:29)
at Setup.main(Setup.java:113)
The point of the Project -> Clean option in Eclipse is to remove your already compiled files in order to build your project again from scratch.
It is likely you ran into a discrepancy between your code and the compiled file, with the compiled file not containing the constructor which was giving a confusing error.
I have found it useful to utilize this option when a confusing error happens, such as not finding something that clearly exists or an import seeming to not work. It is always a good idea to try to Clean to see if it fixes these issues, as it does not take very long to try it out either.
I start Rserve:
C:\Program Files\R\R-3.5.0\bin\x64> "C:\Users\XXXX\DOCUME~1\R\WIN-LI~1\3.5\Rserve\libs\x64\Rserve.exe" --RS-port 1000
Run the following java code:
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;
public class TestR {
private RConnection con;
private RConnection con2;
public TestR(){
try {
con = new RConnection();
con2 = new RConnection();
} catch (RserveException e) {
e.printStackTrace();
}
}
public Double test(){
try {
double d = con.eval("1+1").asDouble();
double c = con2.eval("1+1").asDouble();
return d+c;
} catch (RserveException | REXPMismatchException e) {
return (double)(-1);
}
}
}
I created the following class on JUnit to test it:
import org.junit.Test;
import static org.junit.Assert.*;
public class TestRTest {
#Test
public void test(){
TestR t = new TestR();
t.test();
}
}
When I run this test, it stops while instaciating the connections, it creates the first one, but does hangs on the second. Any idea why this could be happening?
ok
ok
hangs
Your issue might be related to a problem with Multithreading.
Unix: no problem, one Rserve instance can serve mulitple calls.
Windows: Rserve can't create a seperate process by forking the current process.
--> create a new Rserve process for each thread (listening on a different port), a new Rserve connection on the corresponding port has to be established as well.
RConnection connection = new RConnection(HOST, PORT);
If you need more input, do not hesitate to ask. I can also provide my full class code for creating several R instances with Rserve if you want to.
See this Java class I used to run several instances of R with Rserve.
I'm attempting to build a HelloWord websocket client with the example code provided here: https://github.com/Gottox/socket.io-java-client/blob/master/examples/basic/BasicExample.java
The goal is to connect to a Flask server that uses: https://github.com/miguelgrinberg/Flask-SocketIO-Chat The client in python I've built works fine, however I also need to build a java client.
I've seen a lot of different solutions that suggest adding a -cp during compiling, but still get the same message Error: Could not find or load main class TestClient What am I doing wrong?
I'm using this script to compile & run.
#!/bin/sh
export JAVA_HOME="/usr/lib/jvm/java-8-oracle"
/usr/lib/jvm/java-8-oracle/bin/javac TestClient.java -cp /home/erm/git/Flask-SocketIO-Chat/*.jar:*:.:./
echo "exitcode:$?"
/usr/lib/jvm/java-8-oracle/bin/java TestClient
Here's the output:
exitcode:0
Error: Could not find or load main class TestClient
TestClient.java
import io.socket.IOAcknowledge;
import io.socket.IOCallback;
import io.socket.SocketIO;
import io.socket.SocketIOException;
import org.json.JSONException;
import org.json.JSONObject;
public class TestClient implements IOCallback {
private SocketIO socket;
/**
* #param args
*/
public static void main(String[] args) {
System.out.println("Hello, World");
try {
new TestClient();
} catch (Exception e) {
e.printStackTrace();
}
}
public TestClient() throws Exception {
socket = new SocketIO();
socket.connect("http://127.0.0.1:5000/", this);
// Sends a string to the server.
socket.send("Hello Server");
// Sends a JSON object to the server.
socket.send(new JSONObject().put("key", "value").put("key2",
"another value"));
// Emits an event to the server.
socket.emit("event", "argument1", "argument2", 13.37);
}
#Override
public void onMessage(JSONObject json, IOAcknowledge ack) {
try {
System.out.println("Server said:" + json.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onMessage(String data, IOAcknowledge ack) {
System.out.println("Server said: " + data);
}
#Override
public void onError(SocketIOException socketIOException) {
System.out.println("an Error occured");
socketIOException.printStackTrace();
}
#Override
public void onDisconnect() {
System.out.println("Connection terminated.");
}
#Override
public void onConnect() {
System.out.println("Connection established");
}
#Override
public void on(String event, IOAcknowledge ack, Object... args) {
System.out.println("Server triggered event '" + event + "'");
}
}
The error message
Error: Could not find or load main class TestClient
indicates that the Java launcher can't find/load the class file TestClient.class.
To load it properly both the class file itself and the jar file socketio.jar need to be on the class path. So please try
/usr/lib/jvm/java-8-oracle/bin/java -cp .:socketio.jar TestClient
or
/usr/lib/jvm/java-8-oracle/bin/java -cp /home/erm/git/Flask-SocketIO-Chat:/home/erm/git/Flask-SocketIO-Chat/socketio.jar TestClient
The previous answer should work if the file was missing.
But before that, can you please check if the Java file was compiled as it is being run through shell ???
if not please compile the java file
javac TestClient.java
if you are in the path where TestClient.java is present
or provide the full path eg. javac /app/javafiles/TestClient.java
I am learning RMI concepts and had built a simple program taking reference from head first java. All Went fine the first time i ran the code through command prompt.
the next time I ran code the command:
rmiregistry
took too long to load and nothing happened.
I even tried the solution in this thread but nothing happend.
need help to run RMI Registry
also when i run my server and client file i get this error:
Exception: java.rmi.ConnectException: Connection refused to host: 192.168.1.105; nested exception is:
java.net.ConnectException: Connection refused: connect
My Source Code:
myremote.java
import java.rmi.*;
public interface myremote extends Remote
{
public String sayhello() throws RemoteException;
}
Server.java
import java.rmi.*;
import java.rmi.server.*;
public class Server extends UnicastRemoteObject implements myremote
{
public Server() throws RemoteException{}
public String sayhello()
{
return("Server says hi");
}
public static void main(String args[])
{
try
{
myremote S = new Server();
Naming.rebind("remotehello",S);
}
catch(Exception E)
{
System.out.println("Exception: "+E);
}
}
}
client.java
import java.rmi.*;
public class client
{
public static void main(String[] args)
{
client c = new client();
c.go();
}
public void go()
{
try
{
myremote S=(myremote) Naming.lookup("rmi://127.0.0.1/remotehello");
System.out.println("Output:"+S.sayhello());
}
catch(Exception E)
{
System.out.println("Exception: "+ E);
}
}
}
Can't run RMI registry on my system
You've provided no evidence of that.
took too long to load
I don't know what this means. Evidence?
nothing happened.
Nothing is supposed to happen. The RMI registry doesn't print anything. It just sits there.
Run it and try again. You'll be surprised.