2

嗨,我正在尝试在本地主机上的计算机和我的 android 应用程序(目前在模拟器中)之间建立一个简单的套接字连接。我的电脑充当服务器,android 应用程序是客户端。由于某种奇怪的原因,我无法建立连接。我已经尝试了很多方法来做到这一点,但我无法做到。我没有收到任何错误/异常,所以我真的不知道如何在我的项目中走得更远。

服务器代码(桌面程序):

                serverSocket = new ServerSocket(6789);
    while (true) {
        try {
            messageArea.append("\nNow acts as server and waits for mobile to connect.");
            Socket socket = serverSocket.accept(); //blocking state
            messageArea.append("\nMOBILE DEVICE CONNECTED.");
            messageArea.append("\nconnection accepted by:\t :IP" + socket.getInetAddress() + "\t Port:" + socket.getPort() + "\t LocalPort:" + socket.getLocalAddress());

            try {
                createNewStreamsAndListening(socket);
            } catch (ParseException ex) {
                Logger.getLogger(Desktop.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (SocketException e) {
        }
    }

服务器代码应该不是问题。

客户端(Android 应用程序):

-MainActivity.java

public class MainActivity extends Activity
{

private Socket clientSocket = null;
private PrintWriter out;
private BufferedReader in;
boolean run = false;

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

public void onClick(View view) {
        connect();
        createStreamsAndListening();
}

public void connect(){
    try {
        clientSocket = new Socket("127.0.0.1", 6789);
    } catch (UnknownHostException ex) {
        Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
    } 

    if (clientSocket != null) {
        run = true;
    }
}

public void createStreamsAndListening(){
    Thread t = new Thread(
            new Runnable() {
                @Override
                public void run(){;
                    try {
                        out = new PrintWriter(clientSocket.getOutputStream());
                        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                    } catch (IOException ex) {
                        System.err.println("Error in creating Streams:" + ex.toString());
                        return;
                    }

                    String msg = "";

                    while (run) {
                        out.println("Message from client");
                        out.flush();
                        /*try {
                            msg = in.readLine();
                        } catch (IOException ex) {
                            Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
                        }*/
                    }
                }
            });
    t.start();
}

}

-main.xml

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Hello World, MainActivity"
    />

    <Button
        android:id="@+id/myButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="Connect" >
    </Button>

</LinearLayout>

-AndroidManifest.xml

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

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

    <application android:label="@string/app_name" android:icon="@drawable/ic_launcher">
        <activity android:name="MainActivity"
                  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>

客户端甚至根本不连接到服务器。我很感激任何帮助!

4

1 回答 1

3

看起来您缺少有关创建套接字连接的一些部分。不太精通 Java 套接字,但新的 Socket 调用正试图连接到“127.0.0.1”,也称为 localhost。您需要输入服务器的地址。现在它被设置为连接到自身,而不是桌面上的服务器。

public void connect(){
    try {
        clientSocket = new Socket("127.0.0.1", 6789); //<--- this ip address needs
                                                      //     to be fixed.
    } catch (UnknownHostException ex) {
        Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
    } 

    if (clientSocket != null) {
        run = true;
    }
}
于 2013-09-13T16:32:33.680 回答