I'm trying to make a simple server and client program in Eclipse using java but whenever I run the program both consoles output null. Im not sure why this is happening. I read that a common problem is that I've already created an instance of the server and am trying to create another instance but I'm sure thats not the problem. I also read that I might not have root access and need to use a port that is higher than 1024, so I did and I still have the same error.
Server code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Socket_Server_Side {
public static void main(String [] args) throws Exception {
Socket_Server_Side server = new Socket_Server_Side();
server.run();
}
public void run() throws Exception {
ServerSocket SvrSocket = new ServerSocket(1025);
SvrSocket.setReuseAddress(true);
Socket socket = SvrSocket.accept();
InputStreamReader Ir = new InputStreamReader(socket.getInputStream());
BufferedReader Br = new BufferedReader(Ir);
String message = Br.readLine();
System.out.println(message);
if (message != null) {
System.out.println("Message succesfully sent and recieved!");
}
}
}
Client Code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
public class Socket_Client_Side {
public static void main(String [] args) throws Exception{
Socket_Client_Side client = new Socket_Client_Side();
client.run();
}
public void run() throws Exception {
Socket socket2 = new Socket("localhost", 1025);
PrintStream Ps = new PrintStream(socket2.getOutputStream());
Ps.println("Hello Server");
InputStreamReader Ir = new InputStreamReader(socket2.getInputStream());
BufferedReader Br = new BufferedReader(Ir);
String message = Br.readLine();
System.out.println(message);
}
}
From what I can tell, your code works fine. The reason that your client is printing null is due to it not receiving any input itself.
Let's describe the scenario in which you're communicating at a high level.
You have two programs; the server and the client. The server is actively listening for any input to it, and the client sends input to the server. This process is (so far) one-way, and the way we have the code structured, we are only ever writing anything to the server.
Now, you have two channels of communication with a socket: input and output. Recall that we are sending data across to the server, and the server isn't sending any data to the client. This means:
The server should only care about input, and not anything to do with output.
The client should only care about output, and not anything to do with input.
That said, this code in your client is superfluous:
InputStreamReader Ir = new InputStreamReader(socket2.getInputStream());
BufferedReader Br = new BufferedReader(Ir);
String message = Br.readLine();
System.out.println(message);
The reason for this is that your client does not have any input coming in to it, so any messages that did suddenly show up would be a strange thing indeed.
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 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 know how to communicate with a server using a PHP script with JSON, but if the server was written in Java how would I communicate with the server using my Java program.
Would it be the same or is there some easier way that would exclude JSON?
The way I'm used to doing it is using a post request and then encoding/decoding in JSON
it is not a webserver
The most efficient way is to use Sockets. The tutorial does a good job of showing a client/server example.
you can use server socket programming as shown below
as client you can code like this
import java.io.*;
import java.net.*;
public class Client
{
public static void main(String args[])
{
try
{
Socket server;
String str="";
DataInputStream d=new DataInputStream(System.in);
PrintStream toserver;
BufferedReader fromserver;
server=new Socket("117.198.219.36",1096); //your ip to connect and port no through which you will connect to server
InputStreamReader isr=new InputStreamReader(server.getInputStream());
fromserver= new BufferedReader(isr);
toserver=new PrintStream(server.getOutputStream());
while(true)
{
str=":"+d.readLine();
toserver.println(str);
str=fromserver.readLine();
System.out.println(str);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
this is client side program to send request .
Now the server side program is here below in this you will give same port number to connect to client.
import java.io.*;
import java.net.*;
public class Server
{
public static void main(String args[])
{
ServerSocket sc;
Socket client;
DataInputStream d;
PrintStream toClient;
BufferedReader fromClient;
String str="";
try
{
d=new DataInputStream(System.in);
sc=new ServerSocket(1096); //the same port no that we had given at client side
System.out.println("ServerStarted");
client=sc.accept();
InputStreamReader isr=new InputStreamReader(client.getInputStream());
fromClient=new BufferedReader(isr);
toClient=new PrintStream(client.getOutputStream());
while(true)
{
str=fromClient.readLine();
System.out.println(str);
str=":"+d.readLine();
toClient.println(str);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
try to use them you will be able to connect through this .i hope this will help you.
You can communicate as u want, but java developers preffer rpc ( http://en.wikipedia.org/wiki/Remote_procedure_call ) this is the easiest way implement by some frameworks, but if u need full controll of your messages u can do it thought json or even directly through socket (but i dont recommed to do this).