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:
Related
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 am developing a Client-Server application with several other programmers, in Java. At this point in time I do not want to be running the code locally. I want to be able to connect to the Server from any machine.
I wrote a test server and test client, just to make sure that things are working properly. But they are not. I am using Amazon AWS EC2 Linux that comes with Java. I am able to compile and run my Server after I SSH into the EC2, but the Client on my local disk is just not connecting. Here is the code.
// Code found online (https://cs.lmu.edu/~ray/notes/javanetexamples/)
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
public class TestServer {
public static void main(String[] args) throws Exception {
try (ServerSocket listener = new ServerSocket(50000)) {
System.out.println("The capitalization server is running...");
System.out.println(listener.getInetAddress());
ExecutorService pool = Executors.newFixedThreadPool(20);
while (true) {
pool.execute(new Capitalizer(listener.accept()));
}
}
}
private static class Capitalizer implements Runnable {
private Socket socket;
Capitalizer(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
System.out.println("Connected: " + socket);
try {
Scanner in = new Scanner(socket.getInputStream());
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
while (in.hasNextLine()) {
out.println(in.nextLine().toUpperCase());
}
} catch (Exception e) {
System.out.println("Error:" + socket);
} finally {
try { socket.close(); } catch (IOException e) {}
System.out.println("Closed: " + socket);
}
}
}
}
// Code found online (https://cs.lmu.edu/~ray/notes/javanetexamples/)
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class TestClient {
public static void main(String[] args) throws Exception {
try (Socket socket = new Socket("ADDRESS HERE", 50000)) {
System.out.println("Enter lines of text then Ctrl+D or Ctrl+C to quit");
Scanner scanner = new Scanner(System.in);
Scanner in = new Scanner(socket.getInputStream());
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
while (scanner.hasNextLine()) {
out.println(scanner.nextLine());
System.out.println(in.nextLine());
}
}
}
}
In place of "ADDRESS HERE" in the Client, I have tried the private IP and public IP of my Amazon EC2 instance. I have also tried the public DNS name. Nothing seems to work. There is just no connection from the Client to the Server. In fact, "Enter lines of text then Ctrl+D or Ctrl+C to quit" never prints.
All help is appreciated. Thank you.
Allow your IP address to send request to the EC2. For this, you need to go to your Security Group and add your IP there. Follow these steps-
GO to your AWS console.
Click on EC2, then under Resources you will find Security Groups.
Select your security group.
Follow the steps in the given image.
Since you're able to connect to EC2 instance via SSH, your Security Group allows this.
Now you need to allow requests from the client in this Security Group. You will either need to provide a concrete IP, IP range or allow all IPs (not recommended) in the group.
You can find how to do this here.
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 have a server code in Java which I run on my machine and my friend has a client code which runs on his machine. When he enters my IP so as to connect to my server and get the date, connection fails and nothing happens. Note that when I run server and client programs on my own machine and enter localhost as the address, connection is successful and I get the date message correctly. I'm looking for possible errors and problems causing this.
Server code in Java:
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket listener = new ServerSocket(9999);
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();
}
}
}
Client code in Java:
import javax.swing.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class Client {
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 9999:");
Socket s = new Socket(serverAddress, 9999);
BufferedReader input =
new BufferedReader(new InputStreamReader(s.getInputStream()));
String answer = input.readLine();
JOptionPane.showMessageDialog(null, answer);
System.exit(0);
}
}
Some routers might isolate computers in different networks. Try it with both computers on Wifi or both wired to the router. Are your IPs on the same network? Can you see your friend's computer on the network? There might also be some security configurations on your router.
Other than that and firewall issue (which you have disabled), the code looks like it should work fine.
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);
}
}
}