编程语言
首页 > 编程语言> > Android客户端和服务器端编程

Android客户端和服务器端编程

作者:互联网

我正在尝试运行我在网上找到的服务器端和客户端示例.
这是服务器:

public class ServerActivity extends Activity {  

    private TextView serverStatus;  
    private TextView serverStatus2;  

    // DEFAULT IP  
    public static String SERVERIP = "10.100.102.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.activity_server);  
        serverStatus = (TextView) findViewById(R.id.server_status);  
        serverStatus2 = (TextView) findViewById(R.id.server_status2);  

        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() {  
                                serverStatus2.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 (final Exception e) {  
                handler.post(new Runnable() {  
                    @Override  
                    public void run() {  
                        serverStatus.setText("Error" + e.getMessage());  
                    }  
                });  
                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();  
        }  
    }  

}

这是客户的代码:

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.activity_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) {  
                    serverIpserverIpAddress = 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;  
                }  
            }  
        }  
    }

当在同一个eclipse模拟器上运行上面的命令时,服务器抛出异常“Socket Closed”,甚至没有达到while循环“while(true)”.有人知道为什么吗?

这是控制台的输出:

Android Launch!
adb is running normally.
Performing com.example.server.ServerActivity activity launch
Automatic Target Mode: using existing emulator 'emulator-5554' running compatible AVD 'android2.3'
Uploading server.apk onto device 'emulator-5554'
Installing server.apk...
Success!
Starting activity com.example.server.ServerActivity on device emulator-5554
ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.example.server/.ServerActivity }
------------------------------
Android Launch!
adb is running normally.
Performing com.example.client.ClientActivity activity launch
Automatic Target Mode: using existing emulator 'emulator-5554' running compatible AVD 'android2.3'
Application already deployed. No need to reinstall.
Starting activity com.example.client.ClientActivity on device emulator-5554
ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.example.client/.ClientActivity }

这是LogCat输出:

08-08 13:04:38.165: D/ClientActivity(360): C: Connecting...
08-08 13:04:38.176: E/ClientActivity(360): C: Error
08-08 13:04:38.176: E/ClientActivity(360): java.net.ConnectException: /10.0.2.15:50907 - Connection refused
08-08 13:04:38.176: E/ClientActivity(360):  at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:207)
08-08 13:04:38.176: E/ClientActivity(360):  at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
08-08 13:04:38.176: E/ClientActivity(360):  at java.net.Socket.startupSocket(Socket.java:705)
08-08 13:04:38.176: E/ClientActivity(360):  at java.net.Socket.<init>(Socket.java:263)
08-08 13:04:38.176: E/ClientActivity(360):  at com.example.client.ClientActivity$ClientThread.run(ClientActivity.java:58)
08-08 13:04:38.176: E/ClientActivity(360):  at java.lang.Thread.run(Thread.java:1019)
08-08 13:04:40.456: W/IInputConnectionWrapper(360): showStatusIcon on inactive > > > InputConnection

解决方法:

解决了IT,http://developer.android.com/tools/devices/emulator.html.
问题是默认的android模拟器实例只能与自身和以太网交互,因此不同的实例不能相互联网.
如果要这样做,首先必须在实例中设置重定向.
阅读本页它有点像…很多:D

标签:android-networking,android,sockets
来源: https://codeday.me/bug/20190831/1777224.html