Android tcp客户端服务无法连接

时间:2015-11-30 08:08:48

标签: java android tcp android-service

我试着用我的家庭网络和我的应用程序使用移动互联网(4g)连接到我的电脑上运行的java中的服务器,但是它会引发异常,我在做什么?

PS:tcpService.getPlaces方法正在运行。吐司出现但空着。

PS2:抱歉英语不好:(

11-30 02:57:23.430 17607-17607/com.remedialguns.smartourist W/System.err: android.os.NetworkOnMainThreadException
11-30 02:57:23.432 17607-17607/com.remedialguns.smartourist W/System.err:     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
11-30 02:57:23.432 17607-17607/com.remedialguns.smartourist W/System.err:     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:110)
11-30 02:57:23.432 17607-17607/com.remedialguns.smartourist W/System.err:     at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
11-30 02:57:23.432 17607-17607/com.remedialguns.smartourist W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:122)
11-30 02:57:23.432 17607-17607/com.remedialguns.smartourist W/System.err:     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
11-30 02:57:23.432 17607-17607/com.remedialguns.smartourist W/System.err:     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:163)
11-30 02:57:23.432 17607-17607/com.remedialguns.smartourist W/System.err:     at java.net.Socket.startupSocket(Socket.java:590)
11-30 02:57:23.433 17607-17607/com.remedialguns.smartourist W/System.err:     at java.net.Socket.tryAllAddresses(Socket.java:128)
11-30 02:57:23.433 17607-17607/com.remedialguns.smartourist W/System.err:     at java.net.Socket.<init>(Socket.java:178)
11-30 02:57:23.433 17607-17607/com.remedialguns.smartourist W/System.err:     at java.net.Socket.<init>(Socket.java:150)
11-30 02:57:23.433 17607-17607/com.remedialguns.smartourist W/System.err:     at com.remedialguns.smartourist.ConnectionService.test(ConnectionService.java:53)
11-30 02:57:23.433 17607-17607/com.remedialguns.smartourist W/System.err:     at com.remedialguns.smartourist.ListActivity$1.onServiceConnected(ListActivity.java:100)
11-30 02:57:23.433 17607-17607/com.remedialguns.smartourist W/System.err:     at android.app.LoadedApk$ServiceDispatcher.doConnected(LoadedApk.java:1212)
11-30 02:57:23.433 17607-17607/com.remedialguns.smartourist W/System.err:     at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1229)
11-30 02:57:23.433 17607-17607/com.remedialguns.smartourist W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
11-30 02:57:23.433 17607-17607/com.remedialguns.smartourist W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
11-30 02:57:23.433 17607-17607/com.remedialguns.smartourist W/System.err:     at android.os.Looper.loop(Looper.java:135)
11-30 02:57:23.433 17607-17607/com.remedialguns.smartourist W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5312)
11-30 02:57:23.433 17607-17607/com.remedialguns.smartourist W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
11-30 02:57:23.433 17607-17607/com.remedialguns.smartourist W/System.err:     at java.lang.reflect.Method.invoke(Method.java:372)
11-30 02:57:23.433 17607-17607/com.remedialguns.smartourist W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
11-30 02:57:23.433 17607-17607/com.remedialguns.smartourist W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
11-30 02:57:23.605 17607-17617/com.remedialguns.smartourist W/art: Suspending all threads took: 26.858ms

这是我的服务器代码:

public static void main(String[] args) throws Exception {

    String clientSentence;
    String capitalizedSentence;
    ServerSocket welcomeSocket=new ServerSocket(6789);

    while(true){
        Socket connectionSocket = welcomeSocket.accept();
        BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
        DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
        clientSentence = inFromClient.readLine();
        System.out.println("Received: "+clientSentence);
        capitalizedSentence = clientSentence.toUpperCase()+"\n";
        outToClient.writeBytes(capitalizedSentence);
    }

这是我的服务代码:

package com.remedialguns.smartourist;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import android.os.NetworkOnMainThreadException;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Locale;

public class ConnectionService extends Service{


    //Socket s;
    //PrintStream os;
    //public static int serverPort=1001;
    //public static String serverIP="192.168.1.104";
    Place[] PlacesToShow = new Place[10];

    private static final String TAG="com.remedialguns";
    private final IBinder myBinder = new LocalBinder();

    @Override
    public IBinder onBind(Intent intent) {
        return myBinder;
    }

    public void sendProfileData(String userId, String gender,int age, String Country, int[] preferences){
        //send profile data to server
    }

    public String test(){
        String sentence="test";
        String modifiedSentence="";
        try {
            //BufferedReader inFromUser=new BufferedReader(new InputStreamReader(System.in));
            Socket clientSocket = new Socket("190.158.138.160", 6789);//190.158.138.160 //192.168.1.104
            DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
            BufferedReader inFromServer=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            outToServer.writeBytes(sentence+'\n');
            modifiedSentence=inFromServer.readLine();
            Log.d(TAG,modifiedSentence);
            clientSocket.close();
            Toast.makeText(ConnectionService.this,"pls"+modifiedSentence, Toast.LENGTH_SHORT).show();
                    }
        catch (IOException e){
            e.printStackTrace();
        }catch (NetworkOnMainThreadException e){
            e.printStackTrace();
        }
        return modifiedSentence;

    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);

    }





    public Place[] getPlaces(){
        //here a send a String to server and receive an object Place[]



        //F̶a̶k̶e̶ ̶d̶a̶t̶a̶ Test data
        PlacesToShow[0]= new Place("MUSEO","Museo Nacional Agropecuario", 0.15, 0.4, 0.12);
        PlacesToShow[1]= new Place("MUSEO","Museo Arqueológico Junín",0.10, 0.78, 0.44);
        PlacesToShow[2]= new Place("MUSEO","Museo Botero", 0.2, 0.8, 0.08);
        PlacesToShow[3]= new Place("MUSEO","Museo de Zea", 0.3, 0.65, 0.23);
        PlacesToShow[4]= new Place("MUSEO","MUSEO DEL ORO", 0.13, 0.56, 0.12);
        PlacesToShow[5]= new Place("MUSEO","MUSEO DE ARTE COLONIAL", 0.3, 0.67, 0.14);
        PlacesToShow[6]= new Place("MUSEO","MUSEO HISTORICO DE LA POLICIA NACIONAL", 0.34, 0.3, 0.33);
        PlacesToShow[8]= new Place("MUSEO","MUSEO DE LOS NIÑOS", 0.05, 0.65, 0.03);
        PlacesToShow[7]= new Place("MUSEO","Museo Nacional", 0.15, 0.4, 0.12);
        PlacesToShow[9]= new Place("MUSEO","MUSEO MILITAR", 0.07, 0.5, 0.6);
        return PlacesToShow;
    }



    public class LocalBinder extends Binder {
        ConnectionService getService(){
            return ConnectionService.this;
        }
    }
}

这是我的清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.remedialguns.smartourist" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".LoginActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.GET_ACCOUNTS" />
        <uses-permission android:name="android.permission.USE_CREDENTIALS" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar" >
        </activity>
        <activity
            android:name=".RealMainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar" >
        </activity>
        <activity
            android:name=".ListActivity"
            android:label="@string/app_name"
            android:parentActivityName=".RealMainActivity"
            android:theme="@style/AppTheme.NoActionBar" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.remedialguns.smartourist.RealMainActivity" />
        </activity>

        <service
            android:name=".ConnectionService"
            android:enabled="true"
            android:exported="true" >
        </service>
    </application>

</manifest>

1 个答案:

答案 0 :(得分:0)

您正在尝试在主线程上执行网络操作。尝试使用asyntask在后台线程上运行它,或者创建一个单独的线程,无论您喜欢哪个,问题就会消失。

不太好的方法是使用

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

StrictMode.setThreadPolicy(policy); 

如需更好的参考,请参阅This answer