Reputation: 71
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);
}
}
Upvotes: 1
Views: 2082
Reputation: 106450
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:
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.
Upvotes: 3