1

我是 Android Java 编程的新手,所以很难弄清楚我的问题。我有一个简单的 node.js 服务器,它只监听 localhost:7000 并将任何输入打印到控制台(它适用于我的 actionscript 客户端)。我需要做一些类似的事情来理解 Android,只是简单的客户端套接字发送器,它写任何我可以在我的服务器日志中查看的内容。这是代码,我尝试在 Eclipse Android 模拟器上使用,如果我使用“localhost”或“127.0.0.1”,它可以正常工作但没有任何反应(服务器日志将为空),如果我将其更改为我的本地服务器地址(这里是 wi-fi 本地网络和电话使用它)应用程序只是在大冻结然后关闭后抛出错误。电话类似问题。

客户端:

package etc.supachat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;


import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;


public class SupaChatActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
        try {

            Socket s = new Socket("192.168.1.34", 7000);



            //outgoing stream redirect to socket

            OutputStream out = s.getOutputStream();



            PrintWriter output = new PrintWriter(out);

            output.println("Hello Android!");

            BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));



            //read line(s)

            String st = input.readLine();

            //Close connection

            s.close();





    } catch (UnknownHostException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

    } catch (IOException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

    }
    }
}

这是清单代码:

    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".SupaChatActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

这是简单的用户界面:

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/out_view"
            android:layout_width="162dp"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:text="Large Text"
            android:textAppearance="?android:attr/textAppearanceLarge" />

    </RelativeLayout>

</LinearLayout>

更新 这里是 Eclipse 控制台日志:

05-05 18:13:49.172: D/AndroidRuntime(1452): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
05-05 18:13:49.172: D/AndroidRuntime(1452): CheckJNI is ON
05-05 18:13:49.921: D/AndroidRuntime(1452): Calling main entry com.android.commands.pm.Pm
05-05 18:13:49.950: D/AndroidRuntime(1452): Shutting down VM
05-05 18:13:49.971: D/dalvikvm(1452): GC_CONCURRENT freed 101K, 71% free 297K/1024K, external 0K/0K, paused 7ms+1ms
05-05 18:13:49.971: I/AndroidRuntime(1452): NOTE: attach of thread 'Binder Thread #3' failed
05-05 18:13:49.981: D/dalvikvm(1452): Debugger has detached; object registry had 1 entries
05-05 18:13:50.491: D/AndroidRuntime(1462): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
05-05 18:13:50.491: D/AndroidRuntime(1462): CheckJNI is ON
05-05 18:13:51.231: D/AndroidRuntime(1462): Calling main entry com.android.commands.am.Am
05-05 18:13:51.271: I/ActivityManager(68): Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=etc.supachat/.SupaChatActivity } from pid 1462
05-05 18:13:51.321: I/ActivityManager(68): Start proc etc.supachat for activity etc.supachat/.SupaChatActivity: pid=1470 uid=10035 gids={3003}
05-05 18:13:51.362: D/AndroidRuntime(1462): Shutting down VM
05-05 18:13:51.371: D/dalvikvm(1462): GC_CONCURRENT freed 102K, 69% free 319K/1024K, external 0K/0K, paused 1ms+1ms
05-05 18:13:51.421: D/dalvikvm(1462): Debugger has detached; object registry had 1 entries
05-05 18:14:01.324: W/ActivityManager(68): Launch timeout has expired, giving up wake lock!
05-05 18:14:02.033: W/ActivityManager(68): Activity idle timeout for HistoryRecord{406a46a8 etc.supachat/.SupaChatActivity}
05-05 18:14:07.151: D/dalvikvm(137): GC_EXPLICIT freed 47K, 52% free 2817K/5831K, external 4863K/5566K, paused 84ms
05-05 18:16:19.360: I/InputDispatcher(68): Application is not responding: AppWindowToken{407b8948 token=HistoryRecord{406a46a8 etc.supachat/.SupaChatActivity}}.  5036.3ms since event, 5035.8ms since wait started
05-05 18:16:19.360: I/WindowManager(68): Input event dispatching timed out sending to application AppWindowToken{407b8948 token=HistoryRecord{406a46a8 etc.supachat/.SupaChatActivity}}
05-05 18:16:19.491: I/Process(68): Sending signal. PID: 1470 SIG: 3
05-05 18:16:19.491: I/dalvikvm(1470): threadid=4: reacting to signal 3
05-05 18:16:19.520: I/dalvikvm(1470): Wrote stack traces to '/data/anr/traces.txt'
05-05 18:16:19.531: I/Process(68): Sending signal. PID: 68 SIG: 3
05-05 18:16:19.531: I/dalvikvm(68): threadid=4: reacting to signal 3
05-05 18:16:19.580: I/dalvikvm(68): Wrote stack traces to '/data/anr/traces.txt'
05-05 18:16:19.580: I/Process(68): Sending signal. PID: 125 SIG: 3
05-05 18:16:19.590: I/dalvikvm(125): threadid=4: reacting to signal 3
05-05 18:16:19.610: I/dalvikvm(125): Wrote stack traces to '/data/anr/traces.txt'
05-05 18:16:19.610: I/Process(68): Sending signal. PID: 128 SIG: 3
05-05 18:16:19.620: I/dalvikvm(128): threadid=4: reacting to signal 3
05-05 18:16:19.630: I/dalvikvm(128): Wrote stack traces to '/data/anr/traces.txt'
05-05 18:16:20.030: D/dalvikvm(68): GC_EXPLICIT freed 789K, 47% free 4557K/8519K, external 3520K/3903K, paused 112ms
05-05 18:16:20.720: E/ActivityManager(68): ANR in etc.supachat (etc.supachat/.SupaChatActivity)
05-05 18:16:20.720: E/ActivityManager(68): Reason: keyDispatchingTimedOut
05-05 18:16:20.720: E/ActivityManager(68): Load: 0.09 / 0.12 / 0.09
05-05 18:16:20.720: E/ActivityManager(68): CPU usage from 14302ms to 0ms ago:
05-05 18:16:20.720: E/ActivityManager(68):   0.4% 68/system_server: 0.2% user + 0.2% kernel
05-05 18:16:20.720: E/ActivityManager(68):   0.4% 128/com.android.systemui: 0.2% user + 0.1% kernel / faults: 1 minor
05-05 18:16:20.720: E/ActivityManager(68):   0.1% 125/com.android.phone: 0% user + 0.1% kernel
05-05 18:16:20.720: E/ActivityManager(68):   0% 12/pdflush: 0% user + 0% kernel
05-05 18:16:20.720: E/ActivityManager(68):   0% 332/logcat: 0% user + 0% kernel
05-05 18:16:20.720: E/ActivityManager(68): 1.6% TOTAL: 0.9% user + 0.6% kernel
05-05 18:16:20.720: E/ActivityManager(68): CPU usage from 678ms to 1270ms later:
05-05 18:16:20.720: E/ActivityManager(68):   8.3% 68/system_server: 3.3% user + 5% kernel
05-05 18:16:20.720: E/ActivityManager(68):     8.3% 98/InputDispatcher: 6.6% user + 1.6% kernel
05-05 18:16:20.720: E/ActivityManager(68): 13% TOTAL: 6.6% user + 6.6% kernel
05-05 18:16:20.750: I/InputDispatcher(68): Dropping event because the pointer is not down.
05-05 18:16:23.530: W/ActivityManager(68):   Force finishing activity etc.supachat/.SupaChatActivity
05-05 18:16:23.550: I/ActivityManager(68): Killing etc.supachat (pid=1470): user's request
05-05 18:16:23.550: I/Process(68): Sending signal. PID: 1470 SIG: 9
05-05 18:16:23.570: I/ActivityManager(68): Process etc.supachat (pid 1470) has died.
05-05 18:16:23.770: W/InputManagerService(68): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@406c8c68

更新 2.这是与 actionscript-client 一起使用的服务器端脚本(它类似于聊天,我写它是为了理解新的语言和平台):

var net = require("net"), sys = require('util');

var names = Array();
var streams = Array();

var policy = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<!DOCTYPE cross-domain-policy SYSTEM \"http://www.adobe.com/xml/dtds/cross-domain-policy.dtd\">" +
"<cross-domain-policy><allow-access-from domain=\"*\" to-ports=\"*\" />" +
"</cross-domain-policy>\0";

function onStreamData(data){
    var current_stream = this;
    console.log(data);
    if(data.substring(1,20) == "policy-file-request"){
        console.log("asd");
        current_stream.write(policy);
    }

    else if(data.substring(0,6) == "[name]"){
        console.log("name");
        names.push(data.substring(6, data.length));
        streams.push(current_stream);
    }

    else
    {   
        var na;
        for(i =0; i<names.length; i++){
            if(current_stream == streams[i]){
                na = names[i]
            }
        }

        for(i =0; i<names.length; i++){
            if(streams[i]!=null){
                streams[i].write(na+data+"\0");
            }
        }
    }
}

function onClose(){
        var current_stream = this;
        for(i = 0; i<streams.length; i++){
            if(streams == current_stream){
                streams.splice(i, 1);
                names.splice(i, 1);
            }
        }
        current_stream.end();
}

var server = net.createServer(function (stream) {
    stream.setEncoding("utf8");
    stream.on('data', onStreamData);
    stream.on('end', onClose);
});

server.listen(7000, "127.0.0.1");
4

2 回答 2

2

快速修复:主机始终可以通过 IP 地址:10.0.2.2 的模拟器访问, 因此您应该在 android 代码中使用此 IP 地址与主机连接。

更多细节这里):

Android 模拟器与主机所在的网络不同。而是 android 模拟器位于虚拟网络上,位于虚拟路由器后面。因此模拟器无法连接到您主机的私有 IP 地址。(因为它位于不同的网络上)。

当您在 android 代码中使用 localhost(或 127.0.0.1)时,这意味着您要访问 android 设备,因此在您的情况下没有意义。

于 2012-05-05T18:37:26.870 回答
1

要在手机上运行它,您还需要 AndroidManifest.xml 的以下权限:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

我想看看服务器端,因为我没有看到其他错误。

于 2012-05-05T23:54:19.610 回答