isConnected failed: ECONNREFUSED (Connection refused) - javascript

I try to transfer data between phones via wifi-direct and my code works fine everyfirst time I run through it. However, after I close all the sockets in both client and server and try to connect the socket again, it gives me this Exception. Also, after I lock the screen of the server phone and unlock it, I can built up the connection once again. Can someone familar with socket give me any advice?
This shouldn't be about wrong IP address/port right?
CODE for Client phone
protected void onHandleIntent(Intent intent) {
Context context = getApplicationContext();
if (intent.getAction().equals(ACTION_SEND_FILE)) {
if(!socket.isConnected())
{
String host = intent.getExtras().getString(
EXTRAS_GROUP_OWNER_ADDRESS);
int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
try {
socket.bind(null);
InetSocketAddress MyAddress = new InetSocketAddress(host, port);
socket.connect(MyAddress, SOCKET_TIMEOUT);
}
catch(IOException e) {
Log.e(TAG, e.getMessage());
}
}
try{
/*returns an output stream to write data into this socket*/
OutputStream stream = socket.getOutputStream();
String count = String.valueOf(_count);
stream.write(count.getBytes());
} catch (IOException e) {
Log.e(TAG, e.getMessage());
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
InputStream is = socket.getInputStream();
socket.shutdownOutput(); // Sends the 'FIN' on the network
while (is.read() >= 0) ; // "read()" returns '-1' when the 'FIN' is reached
socket.close();
}
catch (IOException e) {
// Give up
e.printStackTrace();
}
}
}
}
}
}
CODE for Server phone
protected String doInBackground(Void... params) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
Socket client = serverSocket.accept();
InputStream inputstream = client.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i;
while ((i = inputstream.read()) != -1) {
baos.write(i);
}
String str = baos.toString();
client.shutdownOutput(); // Sends the 'FIN' on the network
while (inputstream.read() >= 0) ; // "read()" returns '-1' when the 'FIN' is reached
client.close(); // Now we can close the Socket
serverSocket.close();
return str;
} catch (IOException e) {
return null;
}
}

Related

How to send data from Node to another server

I am trying to figure out a way to use Node as a client that would send out data to a server listening on an Android app. The android app will initially send a post request to the Node server with its public IP address and the port it will be listening on (socket). Once there is anything new, the Node server would then send a packet of JSON data onto that particular app via the registered socket.
Is this possible in Node, and if not how can I implement it in Javascript, or what is the best way to implement this?
Here is the Android app server
public class AndroidAppLocalServer {
Activity activity;
ServerSocket serverSocket;
String message = "";
static final int socketServerPORT = 8080;
public AndroidAppLocalServer(Activity activity) {
this.activity = activity;
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
}
public int getPort() {
return socketServerPORT;
}
public void onDestroy() {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerThread extends Thread {
int count = 0;
#Override
public void run() {
try {
// create ServerSocket using specified port
serverSocket = new ServerSocket(socketServerPORT);
while (true) {
// block the call until connection is created and return
// Socket object
Socket socket = serverSocket.accept();
count++;
message += "#" + count + " from "
+ socket.getInetAddress() + ":"
+ socket.getPort() + "\n";
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Log.v("MyApp", message);
}
});
SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(socket, count);
socketServerReplyThread.run();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerReplyThread extends Thread {
private Socket hostThreadSocket;
int cnt;
SocketServerReplyThread(Socket socket, int c) {
hostThreadSocket = socket;
cnt = c;
}
#Override
public void run() {
OutputStream outputStream;
String msgReply = "Hello from AndroidAppLocalServer, you are #" + cnt;
try {
outputStream = hostThreadSocket.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.print(msgReply);
printStream.close();
message += "replayed: " + msgReply + "\n";
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Log.v("MyApp", message);
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message += "Something wrong! " + e.toString() + "\n";
}
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Log.v("MyApp", message);
}
});
}
}
public String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "AndroidAppLocalServer running at : " + inetAddress.getHostAddress();
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
}
Yes you can do this in Node.js, assuming that the App runs on a phone that is actually publicly reachable. Since you are using a plain TCP socket in your Android application, you can verify first by manually connecting the socket by using a tool such as netcat or telnet (e.g., netcat <PUBLIC-IP> 8080).
If this works you can do the same thing from within Node.js by using the net.Socket class.
const net = require('net');
const client = new net.Socket();
client.connect(8080, '<PUBLIC-IP>', () => {
// callback, when connection successfull
client.write('Data sent to the App');
});
client.on('data', (data) => {
// callback, when app replies with data
});
client.on('close', (data) => {
// callback, when socket is closed
});
However, depending on what you actually try to achieve, you might want check out how Android applications usually implement push notifications.

Tableau Integration with Web project

I am doing Tableau integration with web project using java script api. I have configured my ip in tableau server using commnad :tabadmin set wgserver.trusted_hosts "" and respective commands .But I am not able to get the ticket, ended up with -1. I have followed all configuration steps.
public class TableauServlet extends javax.servlet.http.HttpServlet {
private static final long serialVersionUID = 1L;
public TableauServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
final String user = "raghu";
final String wgserver = "103.xxx.xxx.xx";
final String dst = "views/Regional/College?:iid=1";
final String params = ":embed=yes&:toolbar=yes";
String ticket = getTrustedTicket(wgserver, user, request.getRemoteAddr());
if ( !ticket.equals("-1") ) {
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setHeader("Location", "http://" + wgserver + "/trusted/" + ticket + "/" + dst + "?" + params);
}
else
// handle error
throw new ServletException("Invalid ticket " + ticket);
}
// the client_ip parameter isn't necessary to send in the POST unless you have
// wgserver.extended_trusted_ip_checking enabled (it's disabled by default)
private String getTrustedTicket(String wgserver, String user, String remoteAddr)
throws ServletException
{
OutputStreamWriter out = null;
BufferedReader in = null;
try {
// Encode the parameters
StringBuffer data = new StringBuffer();
data.append(URLEncoder.encode("username", "UTF-8"));
data.append("=");
data.append(URLEncoder.encode(user, "UTF-8"));
data.append("&");
data.append(URLEncoder.encode("client_ip", "UTF-8"));
data.append("=");
data.append(URLEncoder.encode(remoteAddr, "UTF-8"));
// Send the request
URL url = new URL("http://" + wgserver + "/trusted");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
out = new OutputStreamWriter(conn.getOutputStream());
out.write(data.toString());
out.flush();
// Read the response
StringBuffer rsp = new StringBuffer();
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ( (line = in.readLine()) != null) {
rsp.append(line);
}
return rsp.toString();
} catch (Exception e) {
throw new ServletException(e);
}
finally {
try {
if (in != null) in.close();
if (out != null) out.close();
}
catch (IOException e) {}
}
}
}
I think you are missing 'target_site' parameter in your URL where you get trusted ticket, its needed if you don't have the 'views/Regional/College' in your default site.
I had gone through a lot of frustration with the '-1' ticket too!
One thing you might try is restarting the tableau server after you have added your web server IP to the trusted_hosts of tableau.
Another thing we ended up doing was adding both the internal ip and external ip of the web server to trusted_hosts on tableau. Since you are using 103.xxx.xxx.xx as your tableau server I am assuming both servers live on the same internal network. You might try that if everything else fails.
My code is almost exactly same as yours and works fine. So if your problem persists, it must be something related to configuration.
here is my code:
private String getAuthenticationTicket(String tableauServerUserName,String tableauServerUrl, String targetSite) {
OutputStreamWriter out = null;
BufferedReader in = null;
try {
StringBuffer data = new StringBuffer();
data.append(URLEncoder.encode("username", Constant.UTF_8));
data.append("=");
data.append(URLEncoder.encode(tableauServerUserName, Constant.UTF_8));
data.append("&");
data.append(URLEncoder.encode("target_site", Constant.UTF_8));
data.append("=");
data.append(URLEncoder.encode(targetSite, Constant.UTF_8));
URL url = new URL(tableauServerUrl + "/" + "trusted");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
out = new OutputStreamWriter(conn.getOutputStream());
out.write(data.toString());
out.flush();
StringBuffer rsp = new StringBuffer();
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
rsp.append(line);
}
return rsp.toString();
} catch (Exception ex) {
//log stuff, handle error
return null;
} finally {
try {
if (in != null)
in.close();
if (out != null)
out.close();
} catch (IOException ex) {
//log stuff, handle error
}
}
}

loading an image file hosted in assets folder exposed with web server in the app

In my app, I have created web server which is hosting a web app. All the files of web app are placed in assets folder.
Now, i start the web server by running my application and then from crome brower, I try to run my web app by calling index.html file. The html, css part of the page is getting loaded properly but the images are not getting loaded in the page:
Here is my HttpRequestHandlerCode:
public class HomePageHandler implements HttpRequestHandler {
private Context context = null;
private static final Map<String, String> mimeTypes = new HashMap<String, String>() {
{
put("css", "text/css");
put("htm", "text/html");
put("html", "text/html");
put("xhtml", "text/xhtml");
put("xml", "text/xml");
put("java", "text/x-java-source, text/java");
put("md", "text/plain");
put("txt", "text/plain");
put("asc", "text/plain");
put("gif", "image/gif");
put("jpg", "image/jpeg");
put("jpeg", "image/jpeg");
put("png", "image/png");
put("svg", "image/svg+xml");
put("mp3", "audio/mpeg");
put("m3u", "audio/mpeg-url");
put("mp4", "video/mp4");
put("ogv", "video/ogg");
put("flv", "video/x-flv");
put("mov", "video/quicktime");
put("swf", "application/x-shockwave-flash");
put("js", "application/javascript");
put("pdf", "application/pdf");
put("doc", "application/msword");
put("ogg", "application/x-ogg");
put("zip", "application/octet-stream");
put("exe", "application/octet-stream");
put("class", "application/octet-stream");
put("m3u8", "application/vnd.apple.mpegurl");
put("ts", " video/mp2t");
}
};
public HomePageHandler(Context context){
this.context = context;
}
#Override
public void handle(HttpRequest request, HttpResponse response, HttpContext httpContext) throws HttpException, IOException {
//String contentType = "text/html";
//Log.i("Sushill", "..request : " + request.getRequestLine().getUri().toString());
final String requestUri = request.getRequestLine().getUri().toString();
final String contentType = contentType(requestUri);
String resp = Utility.openHTMLStringFromAssets(context, "html" + requestUri);
writer.write(resp);
writer.flush();
// }
}
});
((EntityTemplate) entity).setContentType(contentType);
response.setEntity(entity);
}
}
/**
* Get content type
*
* #param fileName
* The file
* #return Content type
*/
private String contentType(String fileName) {
String ext = "";
int idx = fileName.lastIndexOf(".");
if (idx >= 0) {
ext = fileName.substring(idx + 1);
}
if (mimeTypes.containsKey(ext)) {
//Log.i("Sushill", "...ext : " + ext);
return mimeTypes.get(ext);
}
else
return "application/octet-stream";
}
To handle image, I tried this but it did not work :
if(contentType.contains("image")) {
InputStream is = Utility.openImageFromAssets(context, "html" + requestUri);
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Can someone please help me in figuring out how to load the images also in my browser.
Thanks for any help
Do away with BufferedReader(new InputStreamReader' so you do away with UTF-8 too. Use only InputStream 'is'. Do away with writer. You are not showing what 'writer' is but do away with it. Use the OutputStream of the http connection. Keep the buffer and the loop where you read in the buffer and write from the buffer.

Trying to delete source file/ reading file after reading it and writing to new file

I am trying to delete source file which is used for reading. But Delete part is not working. I used code but when I compile it skip to else part
public class delete{
public static void main (String[] args){
BufferedReader br=null;
BufferedWriter bw= null;
String outFileName= "C:\\Users\\dokania\\Desktop\\New folder\\out.txt";
File file1 = new File("C:\\Users\\dokania\\Desktop\\New folder\\casp10.txt");
try{
String s;
int fileCounter=0;
FileWriter fw = new FileWriter(outFileName);
bw = new BufferedWriter(fw);
br=new BufferedReader(new FileReader(file1));
while ((s=br.readLine())!= null){
bw.write(s +"\n");
}
boolean success = (new File (file1.getName())).delete();
if (success)
{
System.out.println(file1.getName()+ "file isdeleted");
}
else
{
System.out.println(file1.getName()+ "file not deleted");
}
}catch(IOException e) {
e.printStackTrace();
}
finally{
try{
if(br!=null){
br.close();
bw.close();
}
}catch(IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
BufferedReader br = null;
BufferedWriter bw = null;
String outFileName = "C:\\Users\\dokania\\Desktop\\New folder\\out.txt";
File file1 = new File("C:\Users\dokania\Desktop\New folder\casp10.txt");
try {
String s;
int fileCounter = 0;
FileWriter fw = new FileWriter(outFileName);
bw = new BufferedWriter(fw);
br = new BufferedReader(new FileReader(file1));
while ((s = br.readLine()) != null) {
bw.write(s + "\n");
}
br.close();
if (file1.delete()) {
System.out.println(file1.getName() + " is deleted!");
} else {
System.out.println("Delete operation is failed.");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
i tried your code it is perfectly working for me.i think just try to refresh the project folder where you keep your files and just use single escape sequence for both file path location

Request a HTTP Request with session from a WebView

I am porting my website to Android using Webview. In my Android app, there is an indicator that shows the number of items in the cart. In Javascript, I call a function named refreshShoppingBadge, that request an AJAX request to update the number. So I write the Javascript Interface for Webview like this:
#JavascriptInterface
public void refreshShoppingBadge(final String pUrl) {
if (pUrl == null) {
return;
}
final DefaultHttpClient request = new DefaultHttpClient();
try {
final HttpResponse response = request.execute(new HttpGet(
this.rootContext + pUrl));
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
Utils.changeTabIndicator(this.tabCartIndex,
String.format(this.tabCartContent, out.toString()));
} else {
Utils.alertNetworkProblem(this.context);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("Shopping", e.getMessage());
} catch (IOException e) {
e.printStackTrace();
Log.e("Shopping", e.getMessage());
}
}
However, the result is always 0, because HttpClient send the request with a new session, so there is nothing in the cart.
Can I "only get result" from the webview, or somehow get its session to request?

Categories

Resources