|
I was doing some Socket tests, and while using localhost everything ran as I wanted. But then I tried to switch it to IP address , and well then things got weird. While the code was in the same class (Code_1 bellow), the simplified test from below was running fine, but as soon as I moved the server code in another project, even another package or class in same package, then when I'm running client code I'm getting java.net.ConnectException: Connection timed out: connect . If when the server is in another project, and for client I'm switching to localhost , then this time it is working. It doesn't want to work when they are in different projects/packages, and the client is using IP address and not localhost , but they work if both are in same project even if client has IP address or localhost .
public static void main(String[] args) throws Exception {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
ServerSocket server = new ServerSocket(port);
Socket socket = server.accept();
System.out.println(new ObjectInputStream(socket.getInputStream()).readObject());
socket.close();
server.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
thread.start();
Socket socket = new Socket("IP_ADDRESS", port);
new ObjectOutputStream(socket.getOutputStream()).writeObject("Test");
socket.close();
}
What is the problem, and what can I do to fix it?
|
|
|
|
|
I found the problem, and it was because the antivirus was blocking network not filtered. I reinstalled it and forgat to add the rule again. But that being said, why was it working when it was in the same class? Was it automatically using localhost in that situation even tho it had a specific IP given?
|
|
|
|
|
I think you are on the right track here.
In your ServerSocket, you did not bind to a specific address, so it likely defaulted to localhost on IPv4. This should also be addressable as 127.0.0.1 which is likely different than the IP used for your local network.
Try “127.0.0.1” for your IP_ADDRESS and see if it works.
There should be a variation of ServerSocket that will let you specify your local network IP address. Using the same IP for server and client should make it work.
Some important commands you can learn:
route print
netstat
ipconfig
|
|
|
|
|
Your client creates a new socket, writes some data to it, and closes it, but that is not how sockets should work. You need to establish a connection in the same way you make a telephone call: call - wait for an answer - talk - say goodbye - close. So both sides should establish the connection first, then run a loop that exchanges data. Only when both sides agree should you close the sockets.
|
|
|
|
|
Then how this signalling should be done? In that simple example the server was only expecting to receive a single object and then it knew it could close because that was all. And on client side the same thing, it knew it only had to send an object and it wasn't goin to receive anything back, so it could close it as that was all.
|
|
|
|
|
Most systems have a protocol that both ends use. So each message has some indicator or flag to tell the peer what type of message is contained in the payload. For example transferring a file between two systems then the receiving station needs to know when the last block is received.
|
|
|
|
|
OK, so there isn't something to specifically tell it, like socket.ImDone(), but in the context they speak to each other. In that case, I'm using something like that in main project. The example in main thread was something simple, to only address java.net.ConnectException: Connection timed out problem, which was in fact caused by antivirus firewall.
|
|
|
|
|
2.1 Define what is meant by a programming paradigm and explain the characteristics of different programming paradigms (Procedural, Object-Oriented, and Event-Driven) (Report).
2.2 Develop Java code examples for a certain scenario of your choice that implements the features and the characteristics of the different programming paradigms (Procedural, Object-Oriented, and Event-Driven). You should utilize the concepts of Encapsulation, Composition, Inheritance, and Polymorphism in your Object-Oriented code. (Code).
2.3 Compare and contrast the features and characteristic of each paradigm that you have used in developing your code in (2.2) (Screenshots of Code) (Report).
2.4 Critically evaluate the code examples that you have developed in (2.2) in terms of code structure and characteristics for each paradigm (Screenshots of Code) (Report).
|
|
|
|
|
Member 15912696 wrote:
full answer with code pls
Err...no thank you.
|
|
|
|
|
No. Nobody is here to do your work, or more importantly, your homework, for you. You learn nothing from that.
Frankly, I find people who ask others to do their work for them lazy and insulting to others and themselves.
|
|
|
|
|
How did lazy make it in here, rap over knuckles a few weeks back pops to mind.
|
|
|
|
|
|
Sounds like "term" stuff ... should cost you about $10,000 for someone else to do it.
"Before entering on an understanding, I have meditated for a long time, and have foreseen what might happen. It is not genius which reveals to me suddenly, secretly, what I have to say or to do in a circumstance unexpected by other people; it is reflection, it is meditation." - Napoleon I
|
|
|
|
|
In order to use JNI, you have to add inside Environment Variables (User or System) the path to were jvm.dll is located. You have a few ways to do that, but it is possible. But, is there a way to not have to add the path inside Environment Variables and instead when you call the function to create a VM from C++ to tell it where it is located via JavaVMInitArgs , or maybe JavaVMOption , or in any other way, but like I said without having to add the path in Environment Variables ?
|
|
|
|
|
 Yes, this is the way I do it, but you can modify it any way you like to provide the path to the library:
#include <Windows.h>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <filesystem> // requires -std:c++17
#include "jni.h"
HMODULE LoadDll(
const char* jrePath
)
{
const char* pszjvmname = "bin\\server\\jvm.dll"; HMODULE hJVMDLL = 0;
std::filesystem::path jvmpath(jrePath);
jvmpath /= pszjvmname;
if (!std::filesystem::exists(jvmpath))
{
std::cerr << "JVM library " << jvmpath << " not found." << std::endl;
}
hJVMDLL = LoadLibraryW(reinterpret_cast<PCWSTR>(jvmpath.c_str()));
if (hJVMDLL != NULL)
{
std::clog << "jvm.dll loaded from: " << jvmpath << std::endl;
}
return hJVMDLL; }
JNIEnv* AttachJVM(
const char* jrePath,
JavaVM* jvm,
std::string strcwd
)
{
HMODULE hJVMDLL = LoadDll(jrePath);
if (hJVMDLL == 0)
{
return nullptr;
}
typedef jint(JNICALL* fpCJV)(JavaVM**, void**, void*);
fpCJV JNI_CreateJavaVM = (fpCJV)::GetProcAddress(hJVMDLL, "JNI_CreateJavaVM");
JavaVMOption options[2];
std::stringstream ssoptions;
ssoptions << "-Djava.class.path=";
ssoptions << strcwd;
std::string stropts = ssoptions.str();
options[0].optionString = const_cast<char*>(stropts.c_str());
options[1].optionString = const_cast<char*>("-verbose:jni");
JavaVMInitArgs vm_args; vm_args.version = JNI_VERSION_1_8;
vm_args.nOptions = 1; vm_args.ignoreUnrecognized = false;
vm_args.options = options;
for (int i = 0; i < vm_args.nOptions; ++i)
{
std::clog << "Options[" << i << "]: " << options[i].optionString << std::endl;
}
JNIEnv* env; jint res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
if (res != 0)
{
std::cerr << "C++: JNI_CreateJavaVM returned: " << res << std::endl;
}
jint version = env->GetVersion();
std::clog << "JVM Version: " << (version >> 16) << "." << (version & 0xffff) << std::endl;
return env; }
void CallClass(
JNIEnv* jniEnv,
const char* pszClassname,
const char* pszMethodname,
const char* pszSignature
)
{
jclass jvmclass = jniEnv->FindClass(pszClassname);
if (jvmclass != NULL)
{
std::cout << "C++: Found the class: " << pszClassname << std::endl;
jmethodID jmid = jniEnv->GetStaticMethodID(jvmclass, pszMethodname, pszSignature);
if (jmid != NULL)
{
std::cout << "C++: Found the method: " << pszMethodname << std::endl;
jniEnv->CallStaticVoidMethod(jvmclass, jmid, NULL);
std::cout << "C++: env->CallStaticVoidMethod complete" << std::endl;
}
else
{
std::cerr << "C++: Failed to find the method: " << pszMethodname << std::endl;
}
}
else
{
std::cerr << "C++: Failed to find the class: " << pszClassname << std::endl;
}
}
int main(
int argc,
const char** argv
)
{
const char* jreDir = nullptr;
std::clog.setstate(std::ios::badbit);
for (argv++; argc > 1; ++argv, --argc)
{
if (*argv[0] == '-')
{
if (strstr(*argv, "-d"))
std::clog.clear();
}
else
{
jreDir = *argv;
}
}
if (jreDir == nullptr)
{
std::cerr << "No root path provided for JVM." << std::endl;
return 1;
}
JNIEnv* jniEnv = NULL;
std::filesystem::path cwd = std::filesystem::current_path();
JavaVM jvm;
jniEnv = AttachJVM(jreDir, &jvm, cwd.string());
if (jniEnv == NULL)
{
std::cerr << "C++: Failed to get Java environment" << std::endl;
return 1;
}
CallClass(jniEnv, "CppToJava", "main", "([Ljava/lang/String;)V");
jint jvmres = jvm.DestroyJavaVM(); std::clog << "C++: DestroyJavaVM and terminate: " << jvmres << std::endl;
}
|
|
|
|
|
Can you include a project with this? I tried it inside a project with c++17 but I'm getting 29 errors.
It marks these lines as problems:
std::filesystem::path jvmpath(jrePath);
jvmpath /= pszjvmname;
if (!std::filesystem::exists(jvmpath)) {
std::filesystem::path cwd = std::filesystem::current_path();
jniEnv = AttachJVM(jreDir, &jvm, cwd.string());
Right now I'm using this to create a VM:
FString UCreateVM::createVM(FString location) {
std::string javaLocation = TCHAR_TO_ANSI(*location);
javaLocation.insert(0, "-Djava.class.path=");
javaLocation.append("Data/Java");
JavaVMInitArgs vm_args;
JavaVMOption* options = new JavaVMOption[1];
options[0].optionString = &javaLocation[0];
vm_args.version = JNI_VERSION_10;
vm_args.nOptions = 1;
vm_args.options = options;
vm_args.ignoreUnrecognized = false;
JNIEnv* env = nullptr;
jint rc = JNI_OK;
if (jvm == nullptr) {
rc = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
}
else {
rc = jvm->AttachCurrentThread((void**)&env, NULL);
}
delete[] options;
if (rc != JNI_OK) {
if (rc == JNI_EVERSION)
return "JNI_EVERSION";
else if (rc == JNI_ENOMEM)
return "JNI_ENOMEM";
else if (rc == JNI_EINVAL)
return "JNI_EINVAL";
else if (rc == JNI_EEXIST)
return "JNI_EEXIST";
else
return "JNI_FATALERROR";
}
return "JNI_CREATED";
}
Also, I should mention that I'm using Eclipse Adoptium Java JRE , and it will be distributed with the app (with all the legal stuff), and in the above function I can add another parameter and tell it where the path for the dll is located inside the app/Eclipse Adoptium Java JRE folder.
modified 26-Jan-23 5:03am.
|
|
|
|
|
I think your option (c++17) may be incorrect, it should be as below. I don't use a project but a simple Makefile. The compile statement that it generates is:
cl -nologo -EHsc -RTC1 -W3 -std:c++17 -I "C:\Program Files\Java\jdk-18.0.2\include" -I "C:\Program Files\Java\jdk-18.0.2\include\win32" cpptojava.cpp
The include paths may well be different on your system.
Your code appears to be OK; what happens when you run it?
|
|
|
|
|
My code is running fine, but I just wanted to skip the step where you have to add the path of the jvm.dll inside Environment variable. Because with this, I need a separate exe file that will first check if the path is added or not (and to add it if it isn't), and after that to launch the exe for the program that is using JNI.
So for this right now I have a Java program that is doing the check and acting as a launcher (which is made using jpackage command, so it doesn't need Java to be installed), and when the check is done it is launching a different exe from its folder.
|
|
|
|
|
Looking at the code, is the following line really what it only needs and the rest are checks if it exists, if it was loader or not?
hJVMDLL = LoadLibraryW(reinterpret_cast<PCWSTR>(jvmpath.c_str()));
|
|
|
|
|
That just loads the library into the process's address space. You still need the dynamic calls to find the method addresses before you can call them, as the library is not linked to the application at build time.
|
|
|
|
|
Would AddDllDirectory with the path of the jvm.dll help with setting another path for the app to look into before it goes to Environment variables? Or that is used for something else and it won't work with JNI? Like I said, I can give the location to the jvm.dll in a parameter, because the location is different for each user, depending where the app is is installed.
|
|
|
|
|
JohnCodding wrote: Would AddDllDirectory with the path of the jvm.dll help I have never used it but the documentation suggests that it would. There's only one way to find out if it works.
|
|
|
|
|
I tried this, but it doesn't work.
std::string dllLocation = "C:\\Program Files\\Eclipse Adoptium\\jdk-18.0.1.10-hotspot\\bin\\server";
std::wstring temp = std::wstring(dllLocation.begin(), dllLocation.end());
AddDllDirectory(temp.c_str());
I also tried to switch it to SetDllDirectory but that also didn't work.
|
|
|
|
|
I might leave it as it is, with the launcher which adds the jvm.dll path to User path if it doesn't exists, and then to launch the actual app. C++ code wording is different then Java, more "raw", and I'm really not use to it, I'm getting lost looking at it and more confused the more I look at examples.
If it aint broke dont fix it. 
modified 26-Jan-23 7:11am.
|
|
|
|
|
I just tried AddDllDirectory also, but it does not seem to do what I expected. I have also been going round in circles trying various changes but basically getting nowhere. I think you are right to stick with a solution that works for you.
|
|
|
|
|