Java - how sockets how can I receive data without constantly pinging - java

Okay, so I have an apache server that has text/data that I want to sendoff to a Java client. The issue is that the data will change often, and I don't want the client to constantly do a read on the server, because obviously I don't want a constant ping. I know that I can make a client socket but that requires my users to port forward to access the server, which isn't going to work for my users.
What I've found online is UDP punching may work or NAT Transfer, but I cant find any examples for how to do it in Java.
If you have any questions please feel free to comment :)

You could Recieve Server-Sent Event notifications, in which the server send the data, using PHP and JS as an example:
var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
PHP:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>

Related

Using a socket for FTP server, but output is not received by client

I'm trying to create a very basic Java FTP server.
The code to handle the incoming socket, accept it, and turn it into a client thread seems to work great, but for some reason it doesn't look like data is getting TO the client when I try to send the welcome message.
// outputstreamwriter for socket
out = new OutputStreamWriter(socket.getOutputStream(),"UTF-8");
// function for sending data
private void send(String s) {
try {
out.write(s,0,s.length());
out.flush();
} catch (IOException e) {
System.out.println("Exception during send(): " + e);
}
System.out.println("> " + s);
}
I see in my console that it is running and trying to send the welcome message, however FileZilla (the FTP client I'm using to connect) usually sits at:
"Connection established, waiting for welcome message..."
===
Edit
The welcome message is pretty basic:
send("220 WELCOME TO THE FTP SERVER");
I'm trying to include only the relevant code because it's far too much to post here. (Listening server thread which launches each client thread, etc.) The point is that it's getting to this point in the code without any problems (i.e. client thread w/ accepted socket ready-to-go) and then when I send data FileZilla appears not to see it.
You need a CR/LF pair at the end of all communication lines. See RFC959:
The File Transfer Protocol follows the specifications of the Telnet
protocol for all communications over the control connection. Since
the language used for Telnet communication may be a negotiated option,
all references in the next two sections will be to the "Telnet
language" and the corresponding "Telnet end-of-line code". Currently,
one may take these to mean NVT-ASCII and <CRLF>. No other
specifications of the Telnet protocol will be cited.

Socket communication between Android app and web browser

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.

Java Socket : Write to client not working

I currently have a problem with a Java server thingy.
It's a simple TCP server which send images. Problem is, I don't have the code of the client program... Moreover, it seems that there is no way to check the client socket for writing event nor the amount of data already sent to the client.
Do someone have any idea about what could prevent the client to get the image correctly ?
Here's my code :
byte[] response = process ( cmd );
if ( response == null )
{
controlSock.close();
dataSock.close();
stop = true;
}
else if ( dataSock != null )
{
dos.write( response );
dos.flush();
}
By the way, the server is working fine with Telnet.
If the server works fine with telnet then your server is fine.
The problem is more likely to be in the assumptions the client is making are not the same as yours. for example the client might assume you are sending the size first in big or little endian format (as an int, short or long) Perhaps it expects the name of the file/image in some format as well.
The only way to know this for sure is to read the code for the client or ask someone who knows what assumptions the client makes.

PHP Socket Server for multiple clients [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
A PHP Socket Server with Flash Clients
I am building an app in my server with the help of a flash developer, and he asked me to build a socket server to communicate with the database. He recommended me JAVA but I am not very good at JAVA and I was wondering if it was possible to build a Socket Server in PHP.
I should allow connections to multiple TCP client connections. I know in JAVA this is done thought threading, but I am not sure if this can also be achieved with PHP.
Could someone please show me the basic skeleton of a PHP Socket Server with these characteristics?
The connection has to be TCp (persistent) from the beginning of the connection to the app, until the end.
You have to run your socket server as a service from the command line.
This is a part of what I have used before. It closes the socket after a read but can easy be modified to keep a array of connections.
You would have to build some kind of watchdog to see if a connection is still alive.
You need a identifying mechanism to identify different connections.
The code:
set_time_limit( 0 );
// Set the ip and port we will listen on
$address = '127.0.0.1';
$port = 6789;
// Create a TCP Stream socket
$sock = socket_create( AF_INET, SOCK_STREAM, 0 ); // 0 for SQL_TCP
// Bind the socket to an address/port
socket_bind( $sock, 0, $port ) or die( 'Could not bind to address' ); //0 for localhost
// Start listening for connections
socket_listen( $sock );
//loop and listen
while (true) {
/* Accept incoming requests and handle them as child processes */
$client = socket_accept( $sock );
// Read the input from the client – 1024000 bytes
$input = socket_read( $client, 1024000 );
// from here you need to do your database stuff
// and handle the response
// Display output back to client
socket_write( $client, $response );
socket_close( $client );
}
// Close the master sockets
socket_close( $sock );
There is a WebSocket Server and Client library for PHP At Google code . It supports flash clients . Not sure whether it solves your problem .
If you want a basic tutorial here is the link to learn
How to create a socket server in php
EDIT :- after looking at your comment ( running a socket server continuously as a service )
Here is the link which describes the way of creating a socket server and running as a process
Create a socket server in php and run as a service
Rather than building a "socket server", you should really build a set of web APIs (SOAP, REST/JSON, whatever) that provides limited and well-defined access to the DB. Then have the Flash app use that.
Your flash app sends JSON over a RESTful interface, or SOAP/XML requests. The server receives them, interacts appropriately with the database, and returns any required results again as XML or JSON.

php sockets read json array from java server

I am connecting to a server written in JAVA using TCP/IP. My application sends json arrays to this server and in some cases also expects some results, json arrays. The problem is that i can easily send json via tcp but when reading it the script freezes waiting forever until it timeouts.
Here is my code.
$sock = socket_create(AF_INET, SOCK_STREAM, 0) //Creating a TCP socket
or die("error: could not create socket\n");
$succ = socket_connect($sock, Application_Model_Config::serverHost, Application_Model_Config::serverPort) //Connecting to to server using that socket
or die("error: could not connect to host\n");
socket_write($sock, $send.'\n', strlen($send)+1);
$response = '';
while ($resp = socket_read($sock, 1024)) {
if (!$resp)
break;
$response .= $resp;
if (strpos($resp, "\n") !== false)
break;
}
echo "Server said: {$response}";
}
$send is a an array encoded as json_encode($array).
Sending is ok but when needed to receive i don't get anything.
I wouldn't mind handling this using jquery (sending and getting json objects from the server) if that would be possible. I am not aware of any implementation that achieves something like this but i'm opened to suggestions...actually would prefer it instead of php.
In the mode you're using socket_read, it has the same semantics as recv:
If no messages are available at the socket, the receive calls wait for a message to arrive, unless the socket is nonblocking (see fcntl(2) ), in which case the value -1 is returned and the external variable errno set to EAGAIN. The receive calls normally return any data available, up to the requested amount, rather than waiting for receipt of the full amount requested.
Therefore, if the script is "waiting forever until it timeouts" that's because there's no data to read. You can confirm this with a packet sniffer.

Categories