Android套接字无法连接到服务器

时间:2013-09-13 16:23:04

标签: android sockets permissions client-server

您好我正试图在我的计算机和本地主机上的我的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>

客户端甚至根本没有连接到服务器。我感谢任何帮助!

1 个答案:

答案 0 :(得分: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;
    }
}