Advertisement

some basic socket questions

Started by February 26, 2017 06:34 AM
20 comments, last by Helo7777 7 years, 8 months ago

Appologies @[member='hplus0603'], I completely missed your reply. Many thanks for the thorough explanation. Yes I actually meant KB, but as usual my fingers been lazy i wrote kb. Thanks

Thanks @[member='TheChubu'], I'm looking into your suggestion right now...

Here is the crash dump, i ran again just now using another port number. @[member='rip-off'], says its a bad idea using netstat port number, following up on that i'm trying 8000, 80, 45210, 8080, it crash-stopped for all ... got to say my novice-ness in socket programming is laid bare now :(

If not in netstat, how do i get the proper port number?

I have no clues what this crash dump says, I only know the crash point by my print-outs. It prints 02 but not 03 so the line code below is the culprit. A disgrace on me that i'm using the elementary method to find the crash line... but sometimes its the quickest


sock = new Socket(serverIP, 45210);

Crash Dump/ STrace


02-26 19:51:46.802: V/qcd(5461):  00
02-26 19:51:46.802: V/qcd(5461):  01
02-26 19:51:46.802: V/qcd(5461):  02
02-26 19:51:46.812: D/AndroidRuntime(5461): Shutting down VM
02-26 19:51:46.812: E/AndroidRuntime(5461): FATAL EXCEPTION: main
02-26 19:51:46.812: E/AndroidRuntime(5461): Process: com.clienserver.fsendfileactivity, PID: 5461
02-26 19:51:46.812: E/AndroidRuntime(5461): android.os.NetworkOnMainThreadException
02-26 19:51:46.812: E/AndroidRuntime(5461): 	at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
02-26 19:51:46.812: E/AndroidRuntime(5461): 	at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:110)
02-26 19:51:46.812: E/AndroidRuntime(5461): 	at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
02-26 19:51:46.812: E/AndroidRuntime(5461): 	at libcore.io.IoBridge.connect(IoBridge.java:122)
02-26 19:51:46.812: E/AndroidRuntime(5461): 	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
02-26 19:51:46.812: E/AndroidRuntime(5461): 	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:163)
02-26 19:51:46.812: E/AndroidRuntime(5461): 	at java.net.Socket.startupSocket(Socket.java:590)
02-26 19:51:46.812: E/AndroidRuntime(5461): 	at java.net.Socket.tryAllAddresses(Socket.java:128)
02-26 19:51:46.812: E/AndroidRuntime(5461): 	at java.net.Socket.<init>(Socket.java:178)
02-26 19:51:46.812: E/AndroidRuntime(5461): 	at java.net.Socket.<init>(Socket.java:150)
02-26 19:51:46.812: E/AndroidRuntime(5461): 	at com.clienserver.fsendfileactivity.FSendfileActivity$2.onClick(FSendfileActivity.java:69)
02-26 19:51:46.812: E/AndroidRuntime(5461): 	at android.view.View.performClick(View.java:5197)
02-26 19:51:46.812: E/AndroidRuntime(5461): 	at android.view.View$PerformClick.run(View.java:20926)
02-26 19:51:46.812: E/AndroidRuntime(5461): 	at android.os.Handler.handleCallback(Handler.java:739)
02-26 19:51:46.812: E/AndroidRuntime(5461): 	at android.os.Handler.dispatchMessage(Handler.java:95)
02-26 19:51:46.812: E/AndroidRuntime(5461): 	at android.os.Looper.loop(Looper.java:145)
02-26 19:51:46.812: E/AndroidRuntime(5461): 	at android.app.ActivityThread.main(ActivityThread.java:5951)
02-26 19:51:46.812: E/AndroidRuntime(5461): 	at java.lang.reflect.Method.invoke(Native Method)
02-26 19:51:46.812: E/AndroidRuntime(5461): 	at java.lang.reflect.Method.invoke(Method.java:372)
02-26 19:51:46.812: E/AndroidRuntime(5461): 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
02-26 19:51:46.812: E/AndroidRuntime(5461): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)

can't help being grumpy...

Just need to let some steam out, so my head doesn't explode...

Looks like the security manager is not allowing you to make a network connection (ie "StrictMode$AndroidBlockGuardPolicy.onNetwork" and "libcore.io.BlockGuardOs.connect").

EDIT:

Another option is coming from "android.os.NetworkOnMainThreadException", which sounds to me like you're not allowed to do network actions on the main thread, which somewhat makes sense, as they might block for a long time, leaving the device dead in the water.

I have no experience with androids, but likely someone has posted about this on the Internet :)

Advertisement

True. You cant make that sort of blocking operation on the main UI thread. Android outright forbids it. So you must look into services: https://developer.android.com/guide/components/services.html

Android Studio has a bunch of templates for that kind of thing. I've made an application that needed such operations working on the background, and its kinda messy. You have to send Intents from the main application, that the services must be registered to listen for, then you must answer those intents from the service, and its not clear when Intent objects get reused or not. Sometimes the operations themselves have to be run from intents. Its awful.

"I AM ZE EMPRAH OPENGL 3.3 THE CORE, I DEMAND FROM THEE ZE SHADERZ AND MATRIXEZ"

My journals: dustArtemis ECS framework and Making a Terrain Generator

Read the stack trace. Google the specific error. The specific error is "android.os.NetworkOnMainThreadException"

enum Bool { True, False, FileNotFound };

Read the stack trace. Google the specific error. The specific error is "android.os.NetworkOnMainThreadException"

This^, when I googled and looked at the various solutions on SO, Chubu's posts began to make more sense to me. It crashes because the network code should run in a separate thread. So i added


new Thread(new Runnable() {
        @Override
        public void run() {
            // added network code here
        }
    }).start();

I doesn't crash anymore

But I've got another problem, it doesn't do anything either.

the code gets stuck at the point where I supply it with the IP and port number (as the prints out indicate), so it was stuck before actually getting the image to the server

Note: at this point the code doesn't really crash or freeze (so no crash dump/stack trace), it only gets stuck waiting, (I'm guessing) it seems to be waiting for the right port number, but I have tried to enter all ports I find on the list after typing “netstat” on the command-line. But each was still the same - stuck on doing nothing

so here is the code, with the comment indicating were it was stuck, waiting. I still don't know how to check for the correct available port, any help with this? thnx


    @Override
            public void onClick(View arg0) {

   //             Socket sock;
            	new Thread(new Runnable() {
                    @Override
                    public void run() {
                    	Socket sock;
                        try {
                            sock = new Socket(serverIP, 8080);      // STUCK WAITING HERE
                            System.out.println("Connecting...");    // NEVER REACHES HERE SO NO PRINTS

                             // sendfile
                              File myFile = new File (selectedImagePath); 
                              byte [] mybytearray  = new byte [(int)myFile.length()];
                              FileInputStream fis = new FileInputStream(myFile);
                              BufferedInputStream bis = new BufferedInputStream(fis);
                              bis.read(mybytearray,0,mybytearray.length);
                              OutputStream os = sock.getOutputStream();
                              System.out.println("Sending...");
                              os.write(mybytearray,0,mybytearray.length);
                              os.flush();
                              sock.close();
                        } catch (UnknownHostException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }                        
                    }
                }).start();
            }
        });
    }

can't help being grumpy...

Just need to let some steam out, so my head doesn't explode...

Well, are you running a server on port 8080?

You shouldn't just enter random port numbers.

You have to have a server listening on that port on that target IP address.

You make that happen by creating a socket, binding it to the port, and listening / accepting on it.

enum Bool { True, False, FileNotFound };
Advertisement

You have to have a server listening on that port on that target IP address. You make that happen by creating a socket, binding it to the port, and listening / accepting on it.

How do I do this in code? Any link on sample code on how this is done? I'm still a novice with this, only trying to use my coding experience in other areas to intuitively pick up logics, but there are often gaps here and there that I can't fill up.

thanks

can't help being grumpy...

Just need to let some steam out, so my head doesn't explode...

Your initial post makes it sound like you already have a server running on your PC?

It might be worth considering pausing work on your project and just writing a few small networking applications to get familiar with the basics. Writing a basic chat server / client is a common starting point, as is a simple HTTP server.

Also consider starting out by using an existing client or server where possible. For example, the "telnet" application is a relatively simple way to send and receive text to and from a given server. You could use your browser to interact with the HTTP server. This way you only have to worry about writing one "half" of the protocol at a time, and you can be confident that the software on the other side is probably functioning correctly.

A simple way of getting a server going is to download and install Python, and write a small Python script that sets up and listens to a socket.

Check for example this super-simple multiplayer example: http://www.enchantedage.com/pymmo

In general, you want to be able to talk to your server using telnet to the port in question (which will send/receive the raw data you type.) If you are using a version of Windows that doesn't come with the command-line "telnet" built in, you can always download putty and set it up to connect using telnet to whatever port your server is listening on.

enum Bool { True, False, FileNotFound };
A simple way of getting a server going is to download and install Python, and write a small Python script that sets up and listens to a socket.

would this Server in python be compatible with an Android/Java client side, and am I correct in assuming that the raw data type that can send/receive (for an initial test) can include bitmap-bytearray streaming for images?

and what of this server code (in Java), why is it not listening or connecting to the client?


import java.io.*;
import java.net.*;

public class FileServer {

    public static void main(String[] args) throws IOException {
        int filesize=500000; // file size temporarily hard coded

        long start = System.currentTimeMillis();
        int bytesRead;
        int current = 0;

        // create socket
        ServerSocket servsock = new ServerSocket(8000);
        while (true) {
          System.out.println("Waiting...");

          Socket sock = servsock.accept();
          System.out.println("Accepted connection : " + sock);

       // receive file
            byte [] mybytearray  = new byte [filesize];
            InputStream is = sock.getInputStream();
            FileOutputStream fos = new FileOutputStream("C:\\myRoot_folder\\image000028.jpg"); // destination path and name of file
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bytesRead = is.read(mybytearray,0,mybytearray.length);
            current = bytesRead;
            do {
               bytesRead =
                  is.read(mybytearray, current, (mybytearray.length-current));
               if(bytesRead >= 0) current += bytesRead;
            } while(bytesRead > -1);

            bos.write(mybytearray, 0 , current);
            bos.flush();
            long end = System.currentTimeMillis();
            System.out.println(end-start);
            bos.close();

            sock.close(); 
            servsock.close();
          }
    }
  
}

 

can't help being grumpy...

Just need to let some steam out, so my head doesn't explode...

This topic is closed to new replies.

Advertisement