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.
Related
I'm trying to make a basic java echo client server app and the textbook I'm reading says I should run the Server.java file first and then the Client.java second. But for some reason VSCode doesn't seem to be doing that. I run my Server.java file and get this which is what I'm expecting:
Simple Echo Server
Waiting for connection.....
And then I go to my Client.java file and run that, but nothing happens there are no errors, it stays at the two lines shown above, I can CTRL+C to terminate the batch job.
I'm expecting it to say this:
Simple Echo Server
Waiting for connection.....
Connected to client
But that's not happening - I am getting no errors though. I don't think it's a problem with my code since it's identical to the textbook's but I'll post it here.
Server.java
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws Exception {
System.out.println("Simple Echo Server");
try (ServerSocket serverSocket = new ServerSocket(6000)) {
System.out.println("Waiting for connection.....");
Socket clientSocket = serverSocket.accept();
System.out.println("Connected to client");
} catch (IOException ex) {
}
}
}
Client.java
import java.io.*;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws Exception {
try {
System.out.println("Waiting for connection.....");
InetAddress localAddress = InetAddress.getLocalHost();
try (Socket clientSocket = new Socket(localAddress, 6000);
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))) {
}
}
catch (IOException ex) {
} // Handle exceptions
}
}
Is it possible that VS code can't run two java files at one time?
EDIT Tried the dual configuration below, but the result is the same, nothing is changing.
It's achievable in VS Code.
Click to create launch.json, keep the default configurations which should be similar to mine in the following picture then add compounds in it:
Turn to the selection box and choose compounds to run by clicking the left green triangle button, you'll get your wanted result:
I am creating a Java HTTP server that checks to make sure a client is not banned before redirecting to the main server. I have already created everything for the server that is needed, I just don't know how to redirect to another port that is running the main server. Here is my code:
package netlyaccesscontrol;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class AllowedCheck {
public static void main(String[] args) {
String line = null;
try {
FileReader reader = new FileReader("Banned.txt");
BufferedReader buffer = new BufferedReader(reader);
ServerSocket s = new ServerSocket(80);
Socket c = s.accept();
String clientIP = c.getInetAddress().toString();
while ((line = buffer.readLine()) != null) {
if (clientIP == line) {
s.close();
} else {
// redirect to main server here
}
}
} catch (FileNotFoundException ex) {
System.out.println("The banned IP address file does not exist.");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
The redirection that you are thinking of is something supported by HTTP and the browsers. There's a specific HTTP response code that tells the caller to redirect and a way to specify it.
Raw sockets are a low-level network protocol that is not going to support redirection as you expect. The most you might be able to do is have this program be a proxy and, upon success, push all incoming data/outgoing responses to/from the ultimate server. But what you have here is by no means going to cut it.
I was trying yesterday to communicate one of my client with my system being the Remote Server and a Client system with Ubuntu 14.04.
The code was about File transfer from Sever to client by passing File reference to the client and client downloading it using the reference,. We were connected to each other through LAN and we able to ping successfully each other's IP(my---10.0.0.2 and his---10.0.0.1).
But,when we ran this code with rmiregistry & on my CentOS Linux and then running Server Side class on my system & his running of java Client class, our connection was done,but, we were unable to pass the file from my system to his system...
The Exception thrown was :-
java.io.FileNotFoundException at Java_Client_1 --- File in = u1.Uploads();
// I have printed the comment on the line having error in the class Java_client_1 class' `main()` method.
Common interface residing on client and server :-
import java.io.*;
import java.rmi.*;
public interface Upload_1 extends Remote {
File Uploads() throws RemoteException;
}
Client Class code :-
import java.io.*;
import java.rmi.*;
import java.rmi.registry.*;
public class Java_Client_1 {
public static void main(String[] args) {
try{
Registry registry=LocateRegistry.getRegistry("10.0.0.2",2000);
Upload_1 u1=(Upload_1)registry.lookup("Uploading");
//File in=new File("/home/ssuman/Public/KALI_LINUX/MyFavourite","something.mp4");
File out=new File("/home/asad/Music","tymaPaulMultithreaded.mp4");
System.out.println("Transferring File---Please be Patient...\n");
File in = u1.Uploads(); // exception thrown here,please check...
FileInputStream fis = new FileInputStream(in);
FileOutputStream fos = new FileOutputStream(out);
byte[] buf = new byte[4096];
int i = 0;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
if (fis != null) fis.close();
if (fos != null) fos.close();
System.out.println("File Successfully Transferred...");
System.out.println("Congratulations,RMI is working successfully!!!");
}
catch(Exception e){
e.printStackTrace();
}
}
}
Server Side Implementer Class :-
import java.io.*;
import java.rmi.*;
import java.rmi.server.*;
public class Java_Uploader_1 extends UnicastRemoteObject implements Upload_1 {
public Java_Uploader_1() throws RemoteException{ }
#Override
public File Uploads() throws RemoteException{
File in = new File("/home/ssuman/Public/KALI_LINUX/MyFavourite","something.mp4");
return in;
}
}
Server Class code :-
import java.rmi.*;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Java_Server_1 {
public static void main(String[] args) {
try{
Registry registry= LocateRegistry.createRegistry(2000);
System.out.println("Ahh,Server Finally Started---GO,GO,GO...\n");
Java_Uploader_1 ju1=new Java_Uploader_1();
registry.rebind("Uploading",ju1);
System.out.println("Service Bound...");
}
catch(Exception e){
System.out.println("An error occured trying to bind the object to the registry.\n"+e);
}
}
}
MY QUESTION:-
Kindly help to resolve this issue OR any alternative for letting remote-client download the file present on my system. And,yes, i want all this to be done using Java RMI, not from CORBA or any othe technology. Thanks in advance for all the commentators and answer posters.
You have to transfer the content of the file.
To do that you have to change the remote interface signature:
public interface Upload_1 extends Remote {
void upload(byte[] content) throws RemoteException;
}
The client send a byte array with the content of the file, and the server takes it and writes to disk.
The problem is when you use large files, the javavm will throw OOME, so you have to simulate streaming over RMI.
Another alternative is using an existing library, take a look at http://openhms.sourceforge.net/rmiio/
A File is essentially a wrapper around a file name on the local file system.
There's no reason to expect it to mean anything to a remote peer.
You need to send the content, not just the name.
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
I want to test this simpel server-client application on my own machine at home. How can I run this in Eclipse and then see if the other side can see my message. I want to at some point be able to make a chat window that anyone could have on their machine and send messages to anyone that is online that is linked into the chat window.
But first I have to be able to see that I have a connection. Should I install a server on my computer, or someone told me that there was a server already installed on my computer but I just had to have windows turn it on. (Windows 7)
Question: How can I test this client-server on my computer at home?
Code:
Client Side:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import javax.swing.JOptionPane;
public class DateClient {
public static void main(String[] args) throws IOException {
String serverAddress = JOptionPane.showInputDialog(
"Enter IP Address of a machine that is\n" +
"running the date service on port 9090:");
Socket s = new Socket(serverAddress, 9090);
BufferedReader input =
new BufferedReader(new InputStreamReader(s.getInputStream()));
String answer = input.readLine();
JOptionPane.showMessageDialog(null, answer);
System.exit(0);
}
}
Server side:
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class DateServer {
public static void main(String[] args) throws IOException {
ServerSocket listener = new ServerSocket(9090);
try {
while (true) {
Socket socket = listener.accept();
try {
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);
out.println(new Date().toString());
} finally {
socket.close();
}
}
}
finally {
listener.close();
}
}
}
Code I want to Add for new message:
out.println("Hello Doug, how are you!);
This will not show in my message box when it shows up on the screen. Is 127.0.0.1 always the IP address that needs to be entered when testing from eclipse or how would I change this around so that I could let the user determine their own IP address.
You can just open two terminals. For the DateClient, just use localhost or 127.0.0.1 as the address. If you really must use Eclipse, then you can run one of the program from Eclipse and the other from a terminal.
You don't need any server.
In Eclipse (assuming your coding is correct), you can run multiple programs (Java files with a main method) simultaneously.
First, say DateServer -> Run As -> Java Application
Next, say DateClient -> Run As -> Java Application
To run this, you don't need any additional server, but Win 7 might ask you for permissions to unblock these programs from accessing the network. You should say yes to these permissions.
If you want to get a feel of separate client and server, this might be better
Keep the DateClient and DateServer in two different projects
Compile both projects as JARs
Open two different DOS consoles and run these two applications in these separate DOS consoles.
Client Side :
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ClientSide {
public static void main(String[] args) {
try {
Socket s = new Socket("localhost", 1234);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF("Hello");
} catch (IOException ex) {
System.out.println("Connection failed");
}
}
}
Server Side :
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
public class ServerSide {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(1234);
System.out.println("waiting for connection...");
DataInputStream dis = new DataInputStream(ss.accept().getInputStream());
System.out.println("Successfully Connected\n" + dis.readUTF());
} catch (IOException ex) {
System.out.println("Server Not Started : " + ex);
}
}
}