Java unknownhostException with two computers - java

import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
public class ChatClient{
private final String serverName;
private final int serverPort;
private Socket socket;
private InputStream serverIn;
private OutputStream serverOut;
public ChatClient(String serverName, int serverPort) {
this.serverName = serverName;
this.serverPort = serverPort;
}
public static void main(String[] args){
ChatClient client = new ChatClient("raspberrypi", 6342);
if (!client.connect()){
System.err.println("Connect failed");
}else{
System.out.println("Connected");
}
}
private boolean connect(){
try{
this.socket = new Socket("raspberrypi", 6342);
this.serverOut = socket.getOutputStream();
this.serverIn = socket.getInputStream();
return true;
}catch (IOException e){
e.printStackTrace();
}
return false;
}
}
I have a server which I am running which is waiting for an client to join. However since I am using the client on my computer and the server on my raspberry pi, I keep getting the unknown host exception. I have tried to put the hostname of the raspberry pi in but it doesn't seem to work. P.s I might be getting the host name wrong.

It does not work, because the value you provide to the first argument (raspberrypi) is not a valid host name.
You need to pass there the IP address of your raspberry in your network.
If you are using home router, you can even set static IP for your raspberry (it's common, because without that, every time you restart your raspberry, you may get different address from DHCP server).
After you know the address of your raspberry, simply replace "raspberrypi" with the address (in form of "192.168.0.10" depending on your configuration).
Here's how to set static IP: https://www.raspberrypi.org/learning/networking-lessons/rpi-static-ip-address/
Edit the file /etc/dhcpcd.conf as follows:
Type sudo nano /etc/dhcpcd.conf at the command prompt.
Scroll to the bottom of the script, and add the following lines:
interface eth0
static ip_address=192.168.0.2/24 static routers=192.168.0.1 static
domain_name_servers=192.168.0.1
interface wlan0
static ip_address=192.168.0.2/24 static routers=192.168.0.1 static
domain_name_servers=192.168.0.1
Save the file with ctrl + o and then
exit nano with ctrl + x. Your Raspberry Pi will now boot up with the
IP address 192.168.0.2 every time; we didn't use 192.168.0.1 as this
is reserved for the router. You can of course use any address you
like, but in the configuration above the range must be between
192.168.0.2 and 192.168.0.255.

Related

Simple SocketHandler for java8 logging(java.util.logging) throws ConnectionException

The intention is to stream the log during runtime on a specific host:port, so that the logs are accessible to users outside the running system, from browser.
As you can see, i have created a simple SocketHandler for java8 logging(java.util.logging), is there something that i have missed?
import java.net.MalformedURLException;
import java.net.URL;
import java.io.IOException;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.SocketHandler;
import java.util.logging.XMLFormatter;
public class Main {
public static void main(String[] args) throws Exception {
Logger logger = Logger.getLogger("concrete.log");
SocketHandler handler = new SocketHandler("HOSTNAME", 19004);
LogRecord logRec = new LogRecord(Level.INFO, "Log recorded");
handler.publish(logRec);
handler.setFormatter(new XMLFormatter());
logger.addHandler(handler);
logger.info("socket handler info message");
}
}
When i run the code, i see the following exception, i have tried checking the system firewall settings on both local(mac/windows) and remote(Linux) and seen that the settings do not block 19004 port
Exception in thread "main" java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:476)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:218)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:394)
at java.net.Socket.connect(Socket.java:606)
at java.net.Socket.connect(Socket.java:555)
at java.net.Socket.<init>(Socket.java:451)
at java.net.Socket.<init>(Socket.java:228)
at java.util.logging.SocketHandler.connect(SocketHandler.java:167)
at java.util.logging.SocketHandler.<init>(SocketHandler.java:154)
at Main.main(Main.java:16)
UPDATE
As suggested by bosowski
When i create Socket to listen to a specific port, the log messages are getting printed on the console of the host. However, am unable to access hostname:port for the log to be streamed from the browser. Is there anything specific that needs to be performed after this step?
Please let me know
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args)
{
try {
ServerSocket ss = new ServerSocket(19004);
Socket soc = ss.accept();
DataInputStream dis
= new DataInputStream(soc.getInputStream());
String str = (String)dis.readUTF();
System.out.println("message= " + str);
ss.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}
SocketHandler does not open up a port to connect to, if that's what you're assuming. It tries to connect to the specified host and port, so you need to have a port that is listening on the host that you are trying to connect to.
https://docs.oracle.com/javase/8/docs/api/java/util/logging/SocketHandler.html#SocketHandler-java.lang.String-int-
<handler-name>.host specifies the target host name to connect to (no default).
<handler-name>.port specifies the target TCP port to use (no default).
If you do indeed have a listening TCP port on the hostname that you're trying to connect to, you can try running sudo nmap -F hostname to check if the port is indeed accessible from your machine.

Running a live Java Server on Amazon AWS

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.

IOS bluetooth serial connection to a remote PC/MAC

I have read about several questions about similar issue. But most of them are related with 3rd party bluetooth device connections. What I need is, to establish a bluetooth serial connection between IOS and a server applet which is waiting for a connection. This applet is supposed to run on Windows or MAC OS. Here is the Java code of the server applet:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import static my.remote.RemoteUI.OSName;
import javax.bluetooth.*;
import javax.microedition.io.*;
import static my.remote.ProcessInput.line;
import static my.remote.RemoteUI.OSName;
/**
* Class that implements an SPP Server which accepts single line of
* message from an SPP client and sends a single line of response to the client.
*/
public class Sspserver implements Runnable {
private static boolean Connected = true;
//start server
private void startServer() throws IOException{
//Create a UUID for SPP
UUID uuid = new UUID("1101", true);
//Create the servicve url
String connectionString = "btspp://localhost:" + uuid +";name=Sample SPP Server";
//open server url
StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );
//Wait for client connection
System.out.println("\nServer Started. Waiting for clients to connect...");
StreamConnection connection=streamConnNotifier.acceptAndOpen();
RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
System.out.println("Remote device address: "+dev.getBluetoothAddress());
System.out.println("Remote device name: "+dev.getFriendlyName(true));
//read string from spp client
InputStream inStream=connection.openInputStream();
BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
while(Connected){
try {
String lineRead=bReader.readLine();
System.out.println(lineRead);
String com = lineRead.substring(0, lineRead.length());
CommandActivity command = new CommandActivity();
if ((lineRead != null) && (OSName != null)) {
command.Command(com,OSName);
System.out.println(com);
}
}catch(Exception e) {
return;
}
}
}
#Override
public void run() {
try {
//display local device address and name
LocalDevice localDevice = LocalDevice.getLocalDevice();
System.out.println("Address: "+localDevice.getBluetoothAddress());
System.out.println("Name: "+localDevice.getFriendlyName());
//Sspserver sampleSPPServer=new Sspserver();
startServer();
} catch (BluetoothStateException ex) {
System.out.println(ex.getMessage());
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
CommandActivity class is just parsing the line of data coming from device. Android devices can easily connect to this server using PC's MAC address. But for IOS I couldn't find any solution for socket connection for bluetooth.
I tried EAAccessoryManager but unfortunately IOS device couldn't detect PC as an accessory. It needs Supported external accessory protocols definitions but I can't find all PC or MAC protocols.
Also I tried CoreBluetooth. But this applet is not advertising name or UUID of services/characteristics.
There must be an easy way which I may be missing. A simple serial connection shouldn't be a problem for an operating system which has lots of features like IOS. Any suggestion appreciated. Thanks.
You cannot estalish a serial port connection from an iOS app over Bluetooth unless the device you are connecting to is MFi certified, which lets you use the external accessory framework. Since your PC is not an MFi certified device, it won't work.
You will either need your PC to advertise as a BLE device so that you can use Core Bluetooth or use an alternative connection method, such as TCP/IP via wifi.

Java RMI for remote ip (host)

I am newbie. I cannot understand RMI correctly. There are tons of tutorials available on the internet ,but all of them are for the local host as I can understand. Both server and client run on the same machine.
I want to run client on any machine and the host will be on the one computer lets consider IP - 11.11.11.11. On the 1099.
But how can I achieve this, where should I specify my IP on the client side. As I understand naming convertion is used, like DNS but anyway when I need to connect to some machine remotely I need to know at least IP address (+mask) and port.
I guess I missed something really important.
Please give some example how to configure RMI remotly not on the same host.
First you have to setup a server whose method or object can be accessed by any remote client
Below is example code for the server.
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface MyCalc extends Remote{
int add(int a, int b) throws RemoteException;
}
import java.rmi.RemoteException;
public class MyCalcImpl implements MyCalc {
#Override
public int add(int a, int b) throws RemoteException {
return (a + b);
}
}
Start the rmi registry on server machine so you can register your object to this registry and better you run it where you have placed your classes otherwise you will get ClassNotFound.
rmiregistry 1099
Note: you might need to change the port if port is already in use.
Register you object to rmi registry with name 'calculator'.
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class MyRMIServer {
public static void main(String[] args) throws Exception {
System.setProperty("java.security.policy","file:///tmp/test.policy");
if (System.getSecurityManager() == null) {
System.setSecurityManager(new SecurityManager());
}
try {
String name = "Calculator";
MyCalc engine = new MyCalcImpl();
MyCalc stub = (MyCalc) UnicastRemoteObject.exportObject(engine, 0);
Registry registry = LocateRegistry.getRegistry(1099);
System.out.println("Registering Calculator Object");
registry.rebind(name, stub);
} catch (Exception e) {
System.err.println("Exception:" + e);
e.printStackTrace();
}
}
}
Note: To run the program you have to setup a security policy file and for that creat a file e.g. test.policy and copy below content.
grant {
permission java.security.AllPermission;
permission java.net.SocketPermission "localhost:1099", "connect, resolve";
permission java.net.SocketPermission "127.0.0.1:1099", "connect, resolve";
permission java.net.SocketPermission "localhost:80", "connect, resolve";
};
You can change IP and port as per your case.
After starting the server, suppose your server's IP address is 11.11.11.11 then you can invoke the MyCalc's add() on the server. So on your client machine your client code would be like:
Copy the MyCalc class from server to client machine so you can set it to the classpath while compiling client's code.
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class MyRMIClient {
public static void main(String args[]) {
System.setProperty("java.security.policy","file:///tmp/test.policy");
if (System.getSecurityManager() == null) {
System.setSecurityManager(new SecurityManager());
}
try {
String name = "Calculator";
String serverIP = "11.11.11.11"; // or localhost if client and server on same machine.
int serverPort = 1099;
Registry registry = LocateRegistry.getRegistry(serverIP, serverPort);
MyCalc mycalc = (MyCalc) registry.lookup(name);
int result = mycalc.add(10, 20);
System.out.println("Result:" + result);
} catch (Exception e) {
System.err.println("ComputePi exception:");
e.printStackTrace();
}
}
}
compile and test the client's code.
EDIT: edited to remove dependency on rmi compiler (rmic)
You only have to specify the server's IP address in one place: the lookup string supplied to Naming.lookup().
[Unless you have the Linux problem referred to in the RMI FAQ item A.1.]

Java Socket Connection Failure

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.

Categories

Resources