Right now I have a Server.java script that is waiting to establish a connection with a listening port. It is currently running on my Amazon instance.
I also have a Client.java file that is trying to send data to the server that is running locally.
Currently the problem is (and if you know about Amazon cloud you know this) the amazon Ubuntu instance requires a private key to confirm the RSA authentication. Is there someway to do this with the socket? I looked at the constructor and could not find anything to give another argument for the key.
to SSH I have to do this i.e. : ssh -i key.pem root#server.amazonaws.com
Client. java
import java.io.PrintWriter;
import java.net.Socket;
class Client {
public static void main(String args[]) {
String data = "toobie ornaught toobie";
try {
Socket skt = new Socket("my ubuntu instance", 1235);
System.out.print("Server has connected!\n");
PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
System.out.print("Sending string: '" + data + "'\n");
out.print(data);
out.close();
skt.close();
} catch (Exception e) {
System.out.print("Whoops! It didn't work!\n");
}
}
}
You are confused. TCP sockets have nothing to do with ssh (except that ssh does use a TCP socket). RSA keys are needed for SSH. You are just opening a plain TCP socket. The keys and other authentication stuff do not apply.
What you need to do is allow your port number through the firewall which is automatically running on EC2 instances.
Related
I'm trying to write an android app that interacts with a server. I'm trying now to write the server side with sockets. I created an instance of ec2 and ran it. I connected to it with putty and ran a simple "hello world" java program. Now I'm trying to run a server which use a socket, but I get this as the server socket: ServerSocket[addr=0.0.0.0/0.0.0.0,localport=5667].
This is my code, very basic so far:
public class EchoServer {
public static void main(String[] args) throws IOException {
int portNumber = 5667;
System.out.println("server socket main");
try (ServerSocket serverSocket = new ServerSocket(portNumber);
) {
System.out.println(serverSocket.toString());
} catch (IOException e) {
System.out
.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
What should I do to run the server so I could connect to it via my andriod device?
Thanks!
You are on the right track. 0.0.0.0 simply means:
A way to specify "any IPv4-interface at all". It is used in this way when configuring servers (i.e. when binding listening sockets).
Next, your server will need to listen for incoming connections by using SocketServer.accept().
And then of course you'll want to receive and send data on the socket. This tutorial should help.
Finally, if you plan on serving multiple clients simultaneously with your server, you will want to consider concurrency and scalability, and perhaps consider using a framework like Netty.
We want to capture the data which comes to the system on port say 7777.
public static void main(String[] args) {
try {
final ServerSocket serverSocket = new ServerSocket(7777);
new Thread("Device Listener") {
public void run() {
try {
System.out.println("Listener Running . . .");
Socket socket = null;
while ((socket = serverSocket.accept()) != null) {
System.out.println("| Incoming : "+ socket.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
We have a device which sends data to the port 7777, which comes with a native windows application. The windows native application is receiving data which comes from that device. We have to receive that data on port 7777 through our java project.
In the above code,
The java server socket is created but no incoming connections are received from the device.
The java server socket is receiving connections from telnet command.
The data format which is used by the device and the other native application may be different, but atleast it has to be connected from java server socket. is it correct?
how to receive the data which is transmitted to port 7777.
EDIT:
Ok, the data is received with UDP socket. it is 68 in length. The device documentation doesn't specify any methods to capture this data, because may be it is designed to work with the specified application. We can't contact the manufacturer also. is there any way (if possible) to know the format of incoming bytes. we have tried network sniffers but we cant understand the format.
If you're receiving from the telnet command, then I suspect you have a network-specific issue.
your device isn't talking to the same ip address / hostname that you're configuring telnet with
you have a routing or firewall issue
is your device possibly using UDP rather than TCP ?
The java server socket is created but no incoming connections are received from the device.
So either there is a firewall in the way or the device isn't trying to connect to that port.
The java server socket is receiving connections from telnet command.
So the Java application is listening to that port.
The data format which is used by the device and the other native application may be different, but at least it has to be connected from java server socket. is it correct?
Yes.
how to receive the data which is transmitted to port 7777.
First you have to accept the connection. On the evidence here the device isn't connecting to port 7777 at all. I suggest some network sniffing is in order to see what it really is doing.
I created a simple echo server in Java. When I try it locally, it works as it should. However, when I try to connect it from a different computer using the IP address and the port number the server is running on, it never connects. Is there anything else that should be done to connect to a server from a different computer?
import java.net.Socket;
import java.net.ServerSocket;
public class EchoServer {
public static void main(String[] args) throws Exception {
// create socket
int port = 4444;
ServerSocket serverSocket = new ServerSocket(port);
System.err.println("Started server on port " + port);
// repeatedly wait for connections, and process
while (true) {
// a "blocking" call which waits until a connection is requested
Socket clientSocket = serverSocket.accept();
System.err.println("Accepted connection from client");
// open up IO streams
In in = new In (clientSocket);
Out out = new Out(clientSocket);
// waits for data and reads it in until connection dies
// readLine() blocks until the server receives a new line from client
String s;
while ((s = in.readLine()) != null) {
out.println(s);
}
// close IO streams, then socket
System.err.println("Closing connection with client");
out.close();
in.close();
clientSocket.close();
}
}
}
Please check the following things.
Is the server computer behind a network proxy ?
Does it have an independent public IP Address by which it is accessible from
anywhere ? Or, does it have an internal IP, by which it can be accessed in your LAN ?
Make sure FireWalls has an exception for port 4444. Or you may turn it of in both client and server.
If it does not help, post the exception you are getting (by editing the question). Or the server program is just freezing without any error ?
If this is on your LAN refer to the machine running your EchoServer by name (the actual machine name, I believe they show you to do it this way on the Sun Tutorial that posted this echo server excercise correct?). If that works it would help a lot in troubleshooting the issue.
I have written a client side java application which communicates through http to a php server. I need to implement a listener on the java (client) side to respond to requests made by the php server. Currently, the java apps are hitting a text file on the server that is updated every minute.
This has worked ok, but now the number of client java apps is rising and this primitive system is starting to break down.
What is the best way to change this? I tried a java ServerSocket listener on the java client app, but can't get that to work. I am having trouble completing the communication. All examples on the web use localhost as ip address example, and my php server is remote hosted.
Do I need to get the ip address of the client machine and send that to the php server so php will know where to send the message? Here is the java code... This is all over the web...
public class MyJavaServer
{
public static void main(String[] args)
{
int port = 4444;
ServerSocket listenSock = null; //the listening server socket
Socket sock = null; //the socket that will actually be used for communication
try
{
System.out.println("listen");
listenSock = new ServerSocket(port);
while (true)
{
sock = listenSock.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
String line = "";
while ((line = br.readLine()) != null)
{
bw.write("PHP said: " + line + "\n");
bw.flush();
}
//Closing streams and the current socket (not the listening socket!)
bw.close();
br.close();
sock.close();
}
}
catch (IOException ex)
{
System.out.println(ex);
}
}
}
... and here is the php
$PORT = 4444; //the port on which we are connecting to the "remote" machine
$HOST = "ip address(not sure here)"; //the ip of the remote machine(of the client java app's computer???
$sock = socket_create(AF_INET, SOCK_STREAM, 0)
or die("error: could not create socket\n");
$succ = socket_connect($sock, $HOST, $PORT)
or die("error: could not connect to host\n");
$text = "Hello, Java!\n"; //the text we want to send to the server
socket_write($sock, $text . "\n", strlen($text) + 1)
or die("error: failed to write to socket\n");
$reply = socket_read($sock, 10000, PHP_NORMAL_READ)
or die("error: failed to read from socket\n");
echo $reply;
This simply does not work. The java app listens, but the php script never connects.
Also, is this the best method for my needs??
Thanks.
The code you include works if the php server machine could connect to the java client machine. In your case that this is all over the web, it means that the java client machine should have an IP that are accessible to public. Once you have it, assign that IP to $HOST, then the code will runs fine.
Assuming that no client can have a public IP, I think the best method is to make your java client talk to your PHP Server in request-reply manner using HTTP request. The java client, acting like a web browser, send a HTTP request and receive HTTP reply that contains data needed by your java client. And when the client numbers rise to a level that you PHP server cannot handle, you could scale it up. Although I haven't had the experience myself, scaling up a PHP server is not uncommon these days.
i'm trying to communicate with my device through java.
I can communicate with it using telnet, i know that because i use PuTTY, so my configuration is:
ip: 192.168.1.4 port: 2001 communication type: telnet
This works, my device and network is working fine.
So i though that i could do the same through java, then i create this class:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
/**
*
* #author Valter
*/
public class Middleware {
public static void main(String args[]) {
try {
Socket socket = new Socket("192.168.1.4", 2001);
// create a channel between to receive data
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
// create a channel between to send data
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF("}Rv!");
// dataOutputStream.flush();
String answer= dataInputStream.readUTF();
System.out.println("Answer:"+answer);
dataInputStream.close();
dataOutputStream.close();
socket.close();
} catch (UnknownHostException ex) {
System.out.println("EXCEÇÃO UNKNOW HOST EXCEPTION");
} catch (IOException ex) {
System.out.println("EXCEÇÃO IOEXCEPTION");
System.out.println(ex.getMessage());
}
}
}
But when i try to execute this, nothing happens, no exceptions, no nothing.
I looks like a 'while' without end.
What should i do here?
I should use a client telnet to java here?
I don't know what sort of device you're talking to, but if you normally type commands to it using telnet, you're presumably sending newlines to it, and perhaps those newlines are needed as command terminators. So perhaps
dataOutputStream.writeUTF("}Rv!\n");
or
dataOutputStream.writeUTF("}Rv!\r\n");
(along with uncommenting that call to flush()) would work better.
What do you really want to send to the device? DataOutputStream#writeUTF uses a Java specific string encoding and I doubt that this is what the device really expects.
Except for that, if the device is really implementing the telnet protocol properly (and not just something which can be accessed with a telnet client), you have to either use a Java telnet library to support control sequences or implement this yourself. You can't just read and write to the socket as in your example code.