Android套接字连接到计算机上未连接的服务器

时间:2015-08-08 22:45:40

标签: android sockets

我最近想要向测试服务器发送请求(在同一个本地wifi上托管),然后在Android应用开发中探索教育。

到目前为止我创建的是我的笔记本电脑上的一个小型快速服务器:

import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;


public class Main {

public static void main(String[] args) throws Exception
{
    System.out.println("Starting...");
    ServerSocket server = new ServerSocket(1234);
    Socket socket = server.accept();
    loop(socket);



}


public static void loop(Socket socket) throws Exception
{

    Scanner socketScanner = new Scanner(socket.getInputStream());
    int num = socketScanner.nextInt();
    System.out.println("Received: " + num);
    num *= 2;

    PrintStream out = new PrintStream(socket.getOutputStream());
    out.println(num);

    loop(socket);
}


}

测试客户端(在笔记本电脑上也很好):

import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;


public class Main {
public static void main(String[] args) throws Exception
{
    Socket socket = new Socket("localhost",1234);

    loop(socket);


}


public static void loop(Socket socket) throws Exception
{
    Scanner scanner = new Scanner(System.in);
    Scanner socketScanner = new Scanner(socket.getInputStream());
    System.out.println("Input number:");
    int num = scanner.nextInt();
    PrintStream p = new PrintStream(socket.getOutputStream());
    p.println(num);

    int response = socketScanner.nextInt();
    System.out.println("Received: " + response);
    loop(socket);
}

}

但后来我尝试从Android Studio连接Android模拟器,并在运行请求后显示一条消息(不幸的是)应用程序已停止。

是的,我已添加用户权限以允许连接?

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.artish1.testapplication" >

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <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>

最后运行实际代码:

 public static  TextView status;
public static EditText ip;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    status = (TextView)findViewById(R.id.statusText);
    ip = (EditText)findViewById(R.id.ipText);
    Log.i(TAG, "Application: onCreate!");

    Button button = (Button)findViewById(R.id.payBenButton);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try{
                status.setText("Sending...");
                Log.i(TAG,"Starting socket sending... to: localhost");
                Socket socket = new Socket("localhost",1234);
                Log.i(TAG, "Connected.");
                int num = Integer.parseInt( ((EditText) findViewById(R.id.numberText)).getText().toString());
                PrintStream out = new PrintStream(socket.getOutputStream());
                out.println(num);
                Log.i(TAG, "Sending: " + num);

                BufferedReader reader = new BufferedReader(new      InputStreamReader(socket.getInputStream()));

                String response = reader.readLine();
                status.setText("Received: " + response);
                Log.i(TAG, "Received: " + response);


            }catch(SocketException e)
            {
                Log.i(TAG,e.getMessage());
            }catch(IOException e)
            {
                Log.i(TAG,e.getMessage());
            }

        }
    });


}

我花了3-4个小时摆弄,但我只是不明白这是什么问题?

3 个答案:

答案 0 :(得分:1)

尝试使用笔记本电脑IP或10.0.2.2 IP替换“localhost”。希望这有帮助!

答案 1 :(得分:0)

没关系,我只需要使用不同的线程。

答案 2 :(得分:0)

  1. 使用完整的URL代替“ localhost”
  2. android:usesCleartextTraffic =“ true” //Add in your menifest