简体   繁体   中英

Connect to server via socket in Android

I am pretty new to android app development, and I have created the following below my activity's onCreate():

public String test(){
    String test = "";
    try{
    Socket s = new Socket(InetAddress.getByName("ipaddress"), port#);
    test +=(s.isConnected());

    BufferedReader readFromHost = new BufferedReader(new InputStreamReader(s.getInputStream()));
    readFromHost.ready();


    test += (readFromHost.readLine());
    s.close();
    }catch(Exception e){
        e.printStackTrace();
    }
    return test;

}

This then just routes to a:

textView2.setText(test());

But the string "test_message" which is grabbed from the server does not appear in the text view. However, When I just do

textView2.setText("hi");

It appears in the view, or if I run the test() in java outside of the android program the resulting "test_message" appears in console. Any thoughts on why it does not appear in the android runtime? Are ports treated differently? Any help would be great.

Attached is the LogCat. There appears to be a "NetworkOnMainThreadException"?

All that occurs in the program is you click a button which opens a new activity with the textview.

Log:

06-09 12:13:18.189: W/ApplicationPackageManager(4768): getCSCPackageItemText()
06-09 12:13:18.239: E/MoreInfoHPW_ViewGroup(4768): Parent view is not a TextView
06-09 12:13:18.369: E/SpannableStringBuilder(4768): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
06-09 12:13:18.369: E/SpannableStringBuilder(4768): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
06-09 12:13:22.773: W/ApplicationPackageManager(4768): getCSCPackageItemText()

06-09 12:13:22.783: W/System.err(4768): android.os.NetworkOnMainThreadException
06-09 12:13:22.783: W/System.err(4768):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1156)
06-09 12:13:22.783: W/System.err(4768):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
06-09 12:13:22.783: W/System.err(4768):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
06-09 12:13:22.783: W/System.err(4768):     at libcore.io.IoBridge.connect(IoBridge.java:112)
06-09 12:13:22.783: W/System.err(4768):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
06-09 12:13:22.783: W/System.err(4768):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
06-09 12:13:22.783: W/System.err(4768):     at java.net.Socket.startupSocket(Socket.java:566)
06-09 12:13:22.783: W/System.err(4768):     at java.net.Socket.<init>(Socket.java:226)
06-09 12:13:22.783: W/System.err(4768):     at com.example.myfirstapp.DisplayMessageActivity.test(DisplayMessageActivity.java:42)
06-09 12:13:22.783: W/System.err(4768):     at com.example.myfirstapp.DisplayMessageActivity.onCreate(DisplayMessageActivity.java:31)
06-09 12:13:22.783: W/System.err(4768):     at android.app.Activity.performCreate(Activity.java:5426)
06-09 12:13:22.783: W/System.err(4768):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
06-09 12:13:22.783: W/System.err(4768):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
06-09 12:13:22.783: W/System.err(4768):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
06-09 12:13:22.783: W/System.err(4768):     at android.app.ActivityThread.access$900(ActivityThread.java:161)
06-09 12:13:22.783: W/System.err(4768):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
06-09 12:13:22.783: W/System.err(4768):     at android.os.Handler.dispatchMessage(Handler.java:102)
06-09 12:13:22.783: W/System.err(4768):     at android.os.Looper.loop(Looper.java:157)
06-09 12:13:22.783: W/System.err(4768):     at android.app.ActivityThread.main(ActivityThread.java:5356)
06-09 12:13:22.783: W/System.err(4768):     at java.lang.reflect.Method.invokeNative(Native Method)
06-09 12:13:22.783: W/System.err(4768):     at java.lang.reflect.Method.invoke(Method.java:515)
06-09 12:13:22.783: W/System.err(4768):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
06-09 12:13:22.783: W/System.err(4768):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
06-09 12:13:22.783: W/System.err(4768):     at dalvik.system.NativeStart.main(Native Method)
06-09 12:13:22.803: E/MoreInfoHPW_ViewGroup(4768): Parent view is not a TextView

You can't do network requests in the Main Thread . Create your own Thread and get string from server:

private TextView textView2;

public void test(){

    new Thread(new Runnable() {
        @Override
        public void run() {
            final StringBuilder test = new StringBuilder();
            try{
                Socket s = new Socket(InetAddress.getByName("ipaddress"), 1111);
                test.append(s.isConnected());

                BufferedReader readFromHost = new BufferedReader(new InputStreamReader(s.getInputStream()));
                readFromHost.ready();


                test.append(readFromHost.readLine());
                s.close();
            }catch(Exception e){
                e.printStackTrace();
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    textView2.setText(test.toString());
                }
            });
        }
    }).start();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM