1

我有两个 android 平板电脑,我想通过套接字编程将消息从客户端发送到服务器。我粘贴了示例代码来制作服务器和客户端应用程序,并将它们安装在两个安卓平板电脑上。都连接到wifi

在客户端应用程序上有一个编辑文本,我应该在其中输入 IP 地址,然后下面的按钮称为“连接电话”。

在单击“连接电话按钮”之前,我应该在编辑文本中输入什么 IP 地址

这是“连接电话”按钮的 onclick 监听器

    private OnClickListener connectListener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        if (!connected) {
            serverIpAddress = serverIp.getText().toString();
            if (!serverIpAddress.equals("")) {
                Thread cThread = new Thread(new ClientThread());
                cThread.start();
            }
        }
    }
};

客户端和服务器应用程序的完整代码如下所示;

客户端代码:

 package com.example.client;

 // import statements

 public class ClientActivity extends Activity {

private EditText serverIp;

private Button connectPhones;

private String serverIpAddress = "";

private boolean connected = false;

private Handler handler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.client);

    serverIp = (EditText) findViewById(R.id.server_ip);
    connectPhones = (Button) findViewById(R.id.connect_phones);
    connectPhones.setOnClickListener(connectListener);
}

private OnClickListener connectListener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        if (!connected) {
            serverIpAddress = serverIp.getText().toString();
            if (!serverIpAddress.equals("")) {
                Thread cThread = new Thread(new ClientThread());
                cThread.start();
            }
        }
    }
};

public class ClientThread implements Runnable {

    public void run() {
        try {
            InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
            Log.d("ClientActivity", "C: Connecting...");
            Socket socket = new Socket(serverAddr, 8080);
            connected = true;
            while (connected) {
                try {
                    Log.d("ClientActivity", "C: Sending command.");
                    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
                                .getOutputStream())), true);
                        // where you issue the commands
                        out.println("Hey Server!");
                        Log.d("ClientActivity", "C: Sent.");
                } catch (Exception e) {
                    Log.e("ClientActivity", "S: Error", e);
                }
            }
            socket.close();
            Log.d("ClientActivity", "C: Closed.");
        } catch (Exception e) {
            Log.e("ClientActivity", "C: Error", e);
            connected = false;
        }
    }
 }
 }

服务器代码;

       package com.example.server;

  // import statements

  public class ServerActivity extends Activity {

private TextView serverStatus;

// default ip
// public static String SERVERIP ="10.0.2.15";

// designate a port
public static final int SERVERPORT = 8080;

private Handler handler = new Handler();

private ServerSocket serverSocket;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.server);
    serverStatus = (TextView) findViewById(R.id.server_status);

    SERVERIP = getLocalIpAddress();

    Thread fst = new Thread(new ServerThread());
    fst.start();
}

    public class ServerThread implements Runnable {

    public void run() {
        try {
            if (SERVERIP != null) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        serverStatus.setText("Listening on IP: " + SERVERIP);
                    }
                });
                serverSocket = new ServerSocket(SERVERPORT);
                while (true) {
                    // listen for incoming clients
                    Socket client = serverSocket.accept();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            serverStatus.setText("Connected.");
                        }
                    });

                    try {
                        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
                        String line = null;
                        while ((line = in.readLine()) != null) {
                            Log.d("ServerActivity", line);
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    // do whatever you want to the front end
                                    // this is where you can be creative
                                }
                            });
                        }
                        break;
                    } catch (Exception e) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones.");
                            }
                        });
                        e.printStackTrace();
                    }
                }
            } else {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        serverStatus.setText("Couldn't detect internet connection.");
                    }
                });
            }
        } catch (Exception e) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    serverStatus.setText("Error");
                }
            });
            e.printStackTrace();
        }
    }
}

// gets the ip address of your phone's network
private String getLocalIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); }
            }
        }
    } catch (SocketException ex) {
        Log.e("ServerActivity", ex.toString());
    }
    return null;
}

@Override
protected void onStop() {
    super.onStop();
    try {
         // make sure you close the socket upon exiting
         serverSocket.close();
     } catch (IOException e) {
         e.printStackTrace();
     }
}

 }

logcat 错误;

01-22 18:37:40.100: E/ClientActivity(19568): C: Error
01-22 18:37:40.100: E/ClientActivity(19568): java.net.ConnectException: failed to connect to /10.0.2.15 (port 8080): connect failed: EHOSTUNREACH (No route to host)
01-22 18:37:40.100: E/ClientActivity(19568):    at libcore.io.IoBridge.connect(IoBridge.java:114)
01-22 18:37:40.100: E/ClientActivity(19568):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
01-22 18:37:40.100: E/ClientActivity(19568):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
01-22 18:37:40.100: E/ClientActivity(19568):    at java.net.Socket.startupSocket(Socket.java:566)
01-22 18:37:40.100: E/ClientActivity(19568):    at java.net.Socket.<init>(Socket.java:225)
01-22 18:37:40.100: E/ClientActivity(19568):    at com.example.client.ClientActivity$ClientThread.run(ClientActivity.java:60)
01-22 18:37:40.100: E/ClientActivity(19568):    at java.lang.Thread.run(Thread.java:856)
01-22 18:37:40.100: E/ClientActivity(19568): Caused by: libcore.io.ErrnoException: connect failed: EHOSTUNREACH (No route to host)
01-22 18:37:40.100: E/ClientActivity(19568):    at libcore.io.Posix.connect(Native Method)
01-22 18:37:40.100: E/ClientActivity(19568):    at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
01-22 18:37:40.100: E/ClientActivity(19568):    at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
01-22 18:37:40.100: E/ClientActivity(19568):    at libcore.io.IoBridge.connect(IoBridge.java:112)
4

3 回答 3

1

When you connect your android device to a WiFi network, it is assigned an IP address. This IP address is visible under the "Settings > About Phone > Status > IP Address" . Now, in your case, the server app runs on one tablet, and client on the other. We need the IP address of the Server only, which you can find out using this method. Enter this IP in the client applications corresponding area, and you're set .

于 2013-12-08T19:33:07.217 回答
0

1.将两个设备与网络(WIFI)连接 2.您可以通过在 android 中以编程方式获取每个设备的 IP 地址 3.并制作一个显示两个 IP 地址的文本视图 4.在两者中键入它来连接它

于 2013-01-23T05:00:38.133 回答
0

您应该在客户端输入服务器 IP 以请求连接。服务器侦听特定端口。如果您的服务器端应用程序显示 IP 地址,请将其放入客户端应用程序以建立连接。如果您的服务器应用程序没有显示任何内容,只需转到设置> 关于> 状态并找到 IP 地址。从您的服务器端代码中,可以清楚地看到:

serverStatus.setText("Listening on IP: " + SERVERIP);

把它放在你的客户端。

于 2013-07-09T21:59:47.713 回答