Establishing connecting using Java RMI - java

I'm writing a program that connects Client machine to Server using RMI and so far I keep getting java.net.ConnectException: Connection refused.
Here is my code;
Interface
public interface ServerInterface extends Remote
{
public String getMessage() throws RemoteException;
}
Server
public class Server extends UnicastRemoteObject implements ServerInterface
{
int portNumber = 7776;
String ipAddress;
Registry registry;
public Server() throws RemoteException
{
try
{
ipAddress = "192.168.0.104";
System.out.println("IP Address: " + ipAddress + " Port Number: " + portNumber);
registry = LocateRegistry.getRegistry();
registry.rebind("ServerFour", this);
}
catch (RemoteException e)
{
System.out.println("Remote Exception Error");
}
}
public String getMessage() throws RemoteException
{
String output = "Connected to Server";
return output;
}
public static void main(String args[])
{
try
{
Server server = new Server();
}
catch (RemoteException ex)
{
System.out.println("Remote Exception in Main");
}
}
}
Client
public class Client
{
public static void main(String[] args) throws NumberFormatException, RemoteException, NotBoundException
{
try
{
ServerInterface server;
Registry registry;
String serverAddress = "192.168.0.104";
String serverPort = "7776";
registry = LocateRegistry.getRegistry(serverAddress, Integer.valueOf(serverPort));
server = (ServerInterface)(registry.lookup("ServerFour"));
String serverMessage = server.getMessage();
System.out.println("Servers Message: " + serverMessage);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
For now I just want Client to call on the method in the ServerInterface and print out its message, but I can't seem to get it to work. I get the Exception message shown above when I start the Client.
When I start the Server it returns this:
IP Address: client4/127.0.1.1 Port Number: 1234
Update:
I've changed the port number to 7776
Ran rmiregistry 7776 &
This is what I get when I start Server and run netstat -anpt
http://i.imgur.com/GXnnG.png
Now on the Client side I'm getting this:
http://i.imgur.com/aBvW3.png

It seems the RMI Registry is bound to localhost (cf. 127.0.0.1 - I assume the 127.0.1.1 is a typo?), yet try to contact it from the client on 192.168.0.104 - that won't work, since nothing presumably is listening on that interface! Try changing the client serverAddress to 127.0.0.1 instead.
The command netstat -anpt (or on Windows: netstat -anbt) is your friend when you want to see what processes are bound on which interfaces (the t is for TCP by the way).
This is the way to bind the Registry to a specific IP (eg. localhost),
registry =
LocateRegistry.
createRegistry( portNumber ,
new RMIClientSocketFactory()
{
#Override
public Socket createSocket( String host, int port ) throws IOException
{
return new Socket( "127.0.0.1" , port );
}
} ,
new RMIServerSocketFactory()
{
#Override
public ServerSocket createServerSocket( int port ) throws IOException
{
return new ServerSocket( port , 0 , InetAddress.getByName( "localhost") );
}
} );
Cheers,

Related

Java: Start a socket server class with the port as an argument

So i have a load balancer and when a server is full of clients i want to create a new multithread server programmatically by passing the server port as an argument.
This is how im trying to start a new server instance
int newport = 4001
SMTPserver server = new SMTPserver();
server.SMTPserver(port);
this is my server
public class SMTPserver {
public static Socket connsock = null;
public static int port;
// SMTPserver(int port) {
// this.port = port;
// }
public static void main(String args[]) throws IOException {
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server is running on port " + port);
while (true) {
try {
// accepting client socket
connsock = serverSocket.accept();
}
}
}
}
my question is how to start this server with the giver port argument? is this code correct?
You are passing 0 to the ServerSocket constructor, so it will choose an available port. You need to pass a non zero port number if you want to use a specific port.
You could do it like this:
public class SMTPserver {
public Socket connsock = null;
public int port;
public SMTPserver(int port) {
this.port = port;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server is running on port " + port);
while (true) {
try {
// accepting client socket
connsock = serverSocket.accept();
}
}
}
}
Notice that I'm assigning the port parameter to the port field, and then passing it to the ServerSocket constructor.

ServerSocket only works on Eclipse - not when embedded to HTML

I have created a program that simply has a server which connects the port (6789) and a client when connects to this same port. However, my issue begins with having the server start and connect to port 6789.
The interesting thing is that my server works perfectly in Eclipse, however when it is embedded in HTML, it does not work although the GUI and other functionalities work. The following code is for starting up my server. I have not included the ClientThread or ServerGUI class since my main issue is getting the server to connect to the port anyways.
Is there another port I should be using instead of 6789 when on HTML?
Thank you!
public class Server {
private ServerGUI sg;
private int port;
// the boolean that will be turned of to stop the server
private boolean keepGoing;
HashSet<String> retailers;
HashSet<String> retailers_company;
ArrayList<HashSet<String>> al;
public Server(int port, ServerGUI sg) {
this.sg = sg;
this.port = port;
}
public void start() {
keepGoing = true;
try
{
ServerSocket serverSocket = new ServerSocket(port);
display("Server started on Port: " + port);
while(keepGoing)
{
Socket socket = serverSocket.accept();
if(!keepGoing)
break;
ClientThread t = new ClientThread(socket);
t.start();
}
try {
serverSocket.close();
}
catch(Exception e) {
display("Exception closing the server and clients: " + e);
}
}
// something went bad
catch (IOException e) {
display("Exception on new ServerSocket: " + e + "\n");
}
}
}

Connecting to web server with java socket class

I am trying to create a simple web proxy app using Java(without using the HTTPUrlConnection class).
I have so far managed to successfully have my server listen on port 10000, and then accept a client connection when I enter a URL into my browser.
I now require my proxy to forward the HTTP request from the browser to the actual web server(the URL which I typed into the browser).
However, I am getting a java.net.UnknownHostException: when attempting to create a socket connection between my proxy and the web server. Does anyone know what may be causing this issue?
Below is the output showing the error aswell as the complete code aswell. Any help is very much appreciated!
Starting the socket server at port:10000
Listening.....
Socket[addr=/127.0.0.1,port=64099,localport=10000]has connected
URL IS http://www.hotmail.com
Can't connect
java.net.UnknownHostException: http://www.hotmail.com
import java.net.*;
import java.io.*;
public class Proxy {
private ServerSocket serverSocket;
private int port;
public Proxy(int port) {
this.port = port; }
public static void main(String[] args) {
int port = 10000;
try {
// initialize the proxy
Proxy proxy = new Proxy(port);
proxy.start();
}
catch (IOException e) {
e.printStackTrace();
}
}
public void start() throws IOException {
System.out.println("Starting the socket server at port:" + port);
serverSocket = new ServerSocket(port);
//Listen for client connection
System.out.println("Listening.....");
Socket client = serverSocket.accept();
//A client has connected to this server
verifyClient(client);
}
private void verifyClient(Socket client) throws IOException {
System.out.println(client + "has connected");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
//Parse the HTTP request from the browser and find the URL
String request;
while ((request = in.readLine()) != null) {
if (request.contains("http://")){
StringBuilder sb = new StringBuilder(request);
sb.delete(0,4);
sb.delete(sb.length()-9,sb.length());
makeConnection(sb.toString());
break;}
in.close();
}
}
private void makeConnection(String url) throws IOException{
//Establish connection between proxy & web server on socket
try {
InetAddress addr;
URL aURL = new URL(url);
System.out.println("URL IS " + aURL.toString());
Socket server = new Socket(urlString,80);
addr = server.getInetAddress();
System.out.println("IP is: " + addr);
System.out.println("Connected to " + addr);
server.close();
}
catch (IOException e) {
System.out.println("Can't connect");
System.out.println(e);
}
}
From your update, it seems like you are trying to create a socket connection to "http://www.hotmail.com". This should just be www.hotmail.com. The "http://" before this is a problem.

testing a client server

I wrote a server that listens for client messages, it's a variation of http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html. I wrote them both in eclipse as java classes in the same project. To test it I have a client class with a main that starts the server and then sends messages to it. When I run it the program just hangs at serverSocket.accept(); according to the javadoc for ServerSocket accept is not asynchronous? That would explain the hanging, but then how does the tutorial code work then?
UPDATE - here is my working code:
Here is the working code:
MyServer.java
/*imports neglected for brevity */
public class MyServer {
public static final String hostname = "localhost";
public static final int portNum = 4444;
ServerSocket serverSocket;
BufferedReader serverReader;
File serverLog;
FileWriter fw;
BufferedWriter serverWriter;
Socket clientSocket;
public static void main(String[] args) {
MyServer server = new MyServer(portNum);
// start the server so it can listen to client messages
server.start();
}
public MyServer(int portNum) {
try {
// endpt for server side, used to listen for client socket
serverSocket = new ServerSocket(portNum);
/* have server socket listen for connection, return client socket.
* serverSocket can now talk to clientSocket
*/
clientSocket = serverSocket.accept();
// server writes messages to this log
serverLog = new File("ServerLog.txt");
if(!serverLog.exists())
serverLog.createNewFile();
fw = new FileWriter(serverLog.getAbsoluteFile());
serverWriter = serverWriter = new BufferedWriter(fw);
/* server reads from this stream that is populated by the client's
* OUTPUT stream/client socket's INPUT stream
*/
serverReader = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream())
);
}
catch (Exception e) {
e.printStackTrace();
}
}
public void start() {
String clientMsg;
try {
while((clientMsg = serverReader.readLine()) != null) {
if(clientMsg.startsWith("exit")) {
break;
}
serverWriter.append(clientMsg);
}
serverWriter.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
MyClient.java
public class MyClient {
public static final String hostname = "localhost";
public static final int portNum = 4444;
public static void main(String[] args) {
String msg = "message 1";
try {
// server is listening on http://localhost:4444
Socket serversSocket = new Socket(hostname, portNum);
PrintWriter clientOut = new PrintWriter(serversSocket.getOutputStream(), true);
// send first message
clientOut.println(msg);
msg = "message 2";
// send second message
clientOut.println(msg);
msg = "exit";
// this will stop the server
clientOut.println(msg);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
If you go through the tutorial it creates two applications one with client one with server.
You cannot create a variation like this as, when you call the constructor, your whole application blocks in clientSocket = serverSocket.accept();.
If you insist on creating a single application for whatever reason, you can do multithreading. But I do not see any reason why you would want to do that.
The tutorial assumes you are not running them in the same program. If you must run them in the same program, then start your server in a separate thread.
if you have an android phone you can test this with the app TCP socket
make sure you PortForward the port the server is listening to.
some isp also block ports so make sure with your isp that all ports are open
trust me broke my head on this one :)
http://docs.oracle.com/javase/6/docs/api/java/net/ServerSocket.html
also make sure your server has the public ip and not local ip
if you test this localy then the code above is fine if not you will need to add
bind(SocketAddress endpoint)
/*Binds the ServerSocket to a specific address (IP address and port number).*/
you can find your ip by typeing in google: whats my ip

Cannot connect using hostname from an Android device

I am trying to connect from my android device to a linux PC using TCP protocol.
Both devices are on the same network.
When I use a simple java code like this on my other PC on the same network, it works and I get an output
class Server {
public static void main ( String[] args ) throws IOException
{
String hostname = "MY_COMPUTER_NAME";
try
{
InetAddress ipaddress = InetAddress.getByName(hostname);
System.out.println("IP address: " + ipaddress.getHostAddress());
}
catch ( UnknownHostException e )
{
System.out.println("Could not find IP address for: " + hostname);
}
}
}
Output:
IP address: 192.168.1.3
When I use this code to connect to a socket on my android phone, it just doesn't work. The handler also updates another TextView for debugging. When I replace MY_COMPUTER_NAME with the actual IP that I can see on my router settings, everything works, the socket is created and the TextView is updated.
//Some variables
String hostname = "MY_COMPUTER_NAME";
private static final int SERVERPORT = 5001;
InetAddress ipaddress = null;
String address = null;
#Override
public void run() {
while(true){
try {
ipaddress = InetAddress.getByName(hostname);
address = ipaddress.getHostAddress();
socket = new Socket(ipaddress, SERVERPORT);
myHandler.post(updateRunnable);
break;
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
What could be the problem, and what am I missing? Thanks.
I think Android has problems with NetBIOS names, but can lookup names that are registered at the DNS Server. see here: Host is unresolved in LAN

Categories

Resources