Socket communication between Android app and web browser - java

My Android device+app is continuously sending data every few ms, and I'd like to receive it on my web browser application that I'm building with JavaScript/HTML.
In the Android/Java app I do the following over socket:
//Initialize, where PORT = local ip of my laptop with web server I guess.
//and I choose an available port on my network, say 8080.
echoSocket = new Socket(HOST, PORT);
out = new PrintWriter(echoSocket.getOutputStream(), true);
//Sending data every few ms:
JSONObject j = new JSONObject();
j.put("x", params[0]);
j.put("y", params[1]);
j.put("z", params[2]);
String jString = j.toString();
out.println(jString);
So I have something like {"x": 1.0023532, "y": 2.454234, "z": 6.234583}.
In other Java applications, I've done this communication by having my receiver application create a ServerSocket on the particular PORT used above. Then as long as I have the right local IP address for my laptop, I can do serverSocket = new ServerSocket(PORT); etc.
Now, how can I accept this data in a web application (JavaScript/HTML)? I've heard of websockets but have no idea how to initialize and use for this purpose - hopefully it's pretty straightforward.

I dont think its possible to send data directly to the browser without a middle man (server). If you want to create a fast and easy server to ping data back and forth I would have some fun with NodeJs. I havent gotten a chance to ever use the stuff but I did have some fun playing with it. It could be something to look into expecially if your just pinging data back and forth between clients.
I watched this video "Introduction to Node.js with Ryan Dahl" a while ago and he showed a basic example that does pretty much what your talking about. Just a thought, plus it would be a fun and fast implementation.
On a side note I do believe Amazon AWS has a instance for Node JS if you want to bring it to a live server. Im pretty sure you can setup a micro instance for no cost.

Related

Sending data to ESP8266 Wi-Fi chip from Android device

I have a ESP8266 chip which is connected to the microcircuit. When chip gets value "200" the light is starting to blink 4 times and than it returns "100" value. I need to make an Android app using Java which will connect to the ESP8266 chip, send data to it and will get value "100". I don't know what library I should use to deal with it. Please, help me, how can I do that? I think it is not the most hard question here.
For your Controller you dont need any Libary. You just can use the serial AT Commands: http://www.electrodragon.com/w/ESP8266
After setting up your ESP like this:
In your App you should deal with TCP-Sockets: https://de.wikibooks.org/wiki/Googles_Android/_TCP-Sockets
Try something like this in an async task:
socket = new Socket();
socket.connect(new InetSocketAddress(ip, port), Connect_Timeout);
DataOutputStream DataOut = new DataOutputStream(socket.getOutputStream());
DataOut.writeBytes(message);
DataOut.flush();
socket.close();
So your ESP is the Server and the App the Client. This should work without problems.

Use Java to connect ethernet device

I had a board connect to the PC using LAN cable(RJ45). I need to write the Java code to connect the board and get some data from it. How can I do it?
Actually I got a code from C++, it used CAsyncSocket class to do it. The C++ code is like this:
CAsyncSocket.Create();
CAsyncSocket.connect(IP, PORT);
Now, I would like to convert it into Java. Actually, I'm not so familiar with Java. Can someone show the code to me?
Example: My board IP is 192.168.2.10 and PORT is 2000. How can I connect it using Java?
see here (for example):
Socket socket = new Socket("192.168.2.10", 2000);
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("Input: " + input.readLine());
socket.close();
http://docs.oracle.com/javase/7/docs/api/java/net/Socket.html
Check out the socket tutorial Lesson: All About Sockets:
URLs and URLConnections provide a relatively high-level mechanism for accessing resources on the Internet. Sometimes your programs require lower-level network communication, for example, when you want to write a client-server application.
See the [http://docs.oracle.com/javase/tutorial/networking/sockets/readingWriting.html](Reading from and Writing to a Socket) example:
Let's look at a simple example that illustrates how a program can establish a connection to a server program using the Socket class and then, how the client can send data to and receive data from the server through the socket.

Android device sends ARP request, no response

Some background:
I'm part of a team that's developing an Android game for a college course.
I am the person in charge of networking, and my aim is to have a game running in "client mode" submit input to a game running in "host mode". The host will then do all physics/collisions etc, and send back the updated state of the game.
I'm confident that I can compress the state of the game enough that sending the whole state of it will work fine (graphics will be done client-side).
I'm aiming have this game work on a wireless LAN, using IPv4 addresses that I get from
NetworkInterface.getNetworkInterfaces().
All activity code and user input is handled outside of my code, so I'm basically working with Java sockets.
Question:
My code below should send a single packet of a single data byte to the host, telling it that there's client who wants to connect. However, I've used Wireshark to trace all packet activity for about 80 seconds after I run this code, and all I can see is
11 2.825742000 MurataMa_41:d5:ed Broadcast ARP 42 Who has 192.168.0.25? Tell 192.168.0.24
That is, an unanswered ARP request. I've tried multiple ports, in case that was the problem, but I'm currently using 5000.
int hostPort = 5000;
hostSocket = new DatagramSocket(hostPort);
byte [] buffer = new byte[1];
buffer[0] = 'h';
DatagramPacket hello = new DatagramPacket(buffer, buffer.length, hostAddress, hostPort);
hostSocket.send(hello);
So, how can I get the host Android device to respond to ARP requests? I have an Android 2.2 phone sending the requests, and a Nexus 7 running Android 4.2.2, which should be receiving them.
EDIT
I've checked LogCat output for any/all exceptions when sending. There are none.

Client-Server communication where Server initiates

I would like to have this setup:
Server hosting TCP socket server
Multiple clients connected over TCP (keeping connection open)
Then I would like to initiate a message from the Server to the client. I can't figure out how to do this, and have multiple client sessions at the same time. Techniques I've read involve the Server listening on a port, and when it receives communicate from a client, it launches a new thread to handle and process that, and then it goes back to listening on the port for the next request of another client.
So, then how would I tap into that and send a message to a client running on one of those threads?
My actual usage scenario if you are interested is below. Final goal is like a remote control for your file system to upload files to the server.
- Each client has a java background application running in the system tray that connects to the server
- Server hosts connections, and also hosts a RESTFul webservice to initiate communication
- Mobile device connects to Server over RESTFul webservices to request informatino about the client's filesystem. So it can drill down and find a file, then click and have the file uploaded to the server.
The idea here is mobile users needing to upload files from their desktop to the server while away from their office on a mobile device. (and this is for custom product, so can't use a third-party app_
PS: I've been looking at the simple Client-Server chat program here: http://way2java.com/networking/chat-program-two-way-communication/
You want to have a server listening at all times on a specified port. Once the server notices an incoming connection on that port you should create a new Thread to handle the communication between that client and the server, while the main thread keeps on listening for other incoming connections. This way you can have multiple clients connected to one server. Like so:
private void listen() throws IOException {
serverSocket = new ServerSocket(port)
while (GlobalFlags.listening) {
new ServerThread(serverSocket.accept();
if (GlobalFlags.exit) {
serverSocket.close();
break;
}
}
}
Where the GlobalFlags are variables to control the listening process and are not really necessary. You could do a while True and just keep listening for ever and ever.
In my project I have a main server controller which had listeners running in Threads. The controller controlled the GlobalFlags. I'm sure instead of using global flags there is a better way to do inter thread communication but for me this was the simplest at the time.
The ServerThread should be looping all the time switching between sending output to the client and receiving input from the client. Like so:
ServerThread(Socket socket) {
super("GameServerThread");
this.socket = socket;
try {
this.socket.setTcpNoDelay(true);
} catch (SocketException e) {
// Error handling
}
this.terminate = false;
}
#Override
public void run() {
try {
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
String inputLine, outputLine;
while ((inputLine = in.readLine()) != null) {
outputLine = processInput(inputLine);
out.println(outputLine);
if (terminate) {
break;
}
}
}
out.close();
in.close();
socket.close();
} catch (Exception e) {
// Error handling, should not use Exception but handle all exceptions by themselves.
}
On the client side you have a thread running through a similar loop, receiving input from the server and then sending output to the server.
In this example processInput is the function used to process the client's input. If you want the server to initiate contact you can make the server send something to the outputstream before listening for input and make the client listen first.
I have extracted this example from one of my own projects and the this.socket.setTcpNoDelay(true) is supposed to make the process faster. Reference here: http://www.rgagnon.com/javadetails/java-0294.html
"java.net.Socket.setTcpNoDelay() is used to enable/disable TCP_NODELAY which disable/enable Nagle's algorithm.
Nagle's algorithm try to conserve bandwidth by minimizing the number of segments that are sent. When applications wish to decrease network latency and increase performance, they can disable Nagle's algorithm (that is enable TCP_NODELAY). Data will be sent earlier, at the cost of an increase in bandwidth consumption. The Nagle's algorithm is described in RFC 896.
You get the current "TCP_NODELAY" setting with java.net.Socket.getTcpNoDelay()"
So to send a message to a specific client you could put all the threads upon creation in an ArrayList so you can keep track of all the currently connected clients. You can have the processInput method halt and polling a queue/variable until another class puts the message to be send in the queue/variable. So how to gain a handle on the class depends on your implementation of processInput. You could give every thread an ID (which is what I did in my project) and maybe have the processInput method poll an ArrayList at index=ID. Then to send output to the client you would have to set the variable at index=ID.
This method seems kind of clunky to me personally but I'm not really sure how else I would do it. You would probably use Queues and have processInput write the input to its Queue and then wait for another class to read it and put its response in the Queue. But I have personally never worked with Queues in java so you should read up on that yourself.
In my knowledge
1) Server hosting TCP socket server -- Possible
2) Multiple clients connected over TCP -- Possible
3) Then I would like to initiate a message from the Server to the client -- Not Possible. The Client has to initiate a connection creation, then the server might be able to send data packets to You. Example: You need to open Facebook website on your browser, Facebook server cannot decide to send its page to your PC on its own because your PC will not have a static IP address, and also if Facebook hypothetically writes code to initiate connection to Your PC, then it is as good as Your PC is the server and Facebook website/server acts as client.

How to transfer data from one jsp to another jsp with sockets

I have 3 .jsp's. The first one asks the user for their username. Once the form is submitted it is taken to a 2nd jsp where a unique passcode is created for the user. How would I go about taking this passcode and passing it to a 3rd jsp using a socket?
You can use java.net.URL and java.net.URLConnection to fire and handle HTTP requests programmatically. They make use of sockets under the covers and this way you don't need to fiddle with low level details about the HTTP protocol. You can pass parameters as query string in the URL.
String url = "http://localhost:8080/context/3rd.jsp?passcode=" + URLEncoder.encode(passcode, "UTF-8");
InputStream input = new URL(url).openStream();
// ... (read it, it contains the response)
This way the passcode request parameter is available in the 3rd JSP by ${param.passcode} or request.getParameter("passcode") the usual way.
Better is however to just include that 3rd JSP in your 2nd JSP.
request.setAttribute("passcode", passcode);
request.getRequestDispatcher("3rd.jsp").include(request, response);
This way the passcode is available as request attribute in the 3rd JSP by ${passcode} or request.getAttribute("passcode") the usual way.
See also:
Using java.net.URLConnection to fire and handle HTTP requests
Unrelated to the concrete question, this is however a terribly nasty hack and the purpose of this is beyond me. There's somewhere a serious design flaw in your application. Most likely those JSPs are tight coupled with business logic which actually belongs in normal and reuseable Java classes like servlets and/or EJBs and/or JAX-WS/RS which you just import and call in your Java class the usual Java way. JSPs are meant to generate and send HTML, not to act as business services, let alone web services. See also How to avoid Java code in JSP files?
So, you want the username to be submitted from the first JSP to the second, by submitting a form to the second, right?
But, for interaction between the second and third, you want to avoid using the communication mechanisms behind the the JSP files and use your own, right?
Well, how you might implement doing this depends on where you're sending your communication from and to. For instance, are they on the same machine, or on different machines?
Generally speaking, you'll need a client-server type of relationship to be set up here. I imagine that you would want your third JSP to act as the server.
What the third JSP will do is will sit and wait for a client to try to communicate with it. But, before you can do that, you'll first need to bind a port to your application. Ports are allocated by the Operating System and are given to requesting processes.
When trying to implement this in Java, you might want to try something like the following:
int port_number = 1080;
ServerSocket server = new ServerSocket(port_number);
In the above example, the ServerSocket is already bound to the specified port 1080. It doesn't have to be 1080 - 1080 is just an example.
Next, you will want to listen and wait for a request to come in. You can implement this step in the following:
Socket request = null;
while((request = server.accept()) == null)
{}
This will cause the server socket to keep looping until it finally receives a request. When the request comes in, it will create a new Socket object to handle that request. So, you could come back to your loop later on and continue to wait and accept requests, while a child thread handles communication using your newly created request Socket.
But, for your project, I would guess that you don't need to communicate with more than one client at a time, so it's okay if we just simply stop listening once we receive a request, I suppose.
So, now onto the client application. Here, it's a little bit different from what we had with the server. First off, instead of listening in on the port and waiting for are request, the client's socket will actively try to connect to a remote host on their port. So, if there is no server listening in on that port, then the connection will fail.
So, two things will need to be know, those are:
What's the IP Address of the server?
What port is the server listening in on?
There are short-cuts to getting the connection using the Java Socket class, but I assume that you're going to test this out on the same machine, right? If so, then you will need two separate ports for both your client and server. That's because the OS won't allow two separate processes to share the same port. Once a process binds to the port, no other process is allowed to access it until that port releases it back to the OS.
So, to make the two separate JSP's communicate on the same physical machine, you'll need both a local port for your client, and you'll need the server's port number that it's listening in on.
So, let's try the following for the client application:
int local_port = 1079;
int remote_port = 1080;
InetSocketAddress localhost = new InetSocketAddress(local_port);
Socket client = new Socket(); //The client socket is not yet bound to any ports.
client.bind(localhost); //The client socket has just requested the specified port number from the OS and should be bound to it.
String remoteHostsName = "[put something here]";
InetSocketAddress remotehost = new InetSocketAddress(InetAddress.getByName(remoteHostsName), remote_port); //Performs a DSN lookup of the specified remote host and returns an IP address with the allocated port number
client.connect(remotehost); //Connection to the remote server is being made.
That should help you along your way.
A final note should be made here. You can't actually run these two applications using the same JVM. You'll need two separate processes for client and server applications to run.

Categories