Use Eclipse to build a simple Android server

1. Environment Construction

1. List of required software

a、 Tomcat

b、Eclipse

c、JDK

2. Environment configuration

Tomcat configuration, JDK installation, note that if the Tomcat plug-in is not installed in Eclipse (there is no Server and Tomcat in Windows-->Preferences), you can refer to  https://blog.csdn.net/suyimin2010/article/details/80050202Install Tomcat plugin.


Second, the project configuration

1. Server

1.1 Create a new Web Project in File-->new--->Dynamic Web Project in Eclipse

1.2 Create a new package and Main class under Java Resources, and write the following code: 

package com.chatfree.server;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Main {
    public static final int PORT = 8888;//Listening port number   

    public static void main(String[] args) {
        System.out.println("Server started...\n");
        Main server = new Main();
        server.init();
    }

    public void init() {
        try {
            ServerSocket serverSocket = new ServerSocket(PORT);
            while (true) {
                // Once there is a blockage, it means that the server and the client have obtained a connection  
                Socket client = serverSocket.accept();
                // handle this connection  
                new HandlerThread(client);
            }
        } catch (Exception e) {
            System.out.println("Server exception: " + e.getMessage());
        }
    }

    private class HandlerThread implements Runnable {
        private Socket socket;
        public HandlerThread(Socket client) {
            socket = client;
            new Thread(this).start();
        }

        public void run() {
            try {
                // read client data  
                DataInputStream input = new DataInputStream(socket.getInputStream());
                String clientInputStr = input.readUTF();//It should be noted that it corresponds to the writing method of the client output stream, otherwise an EOFException will be thrown
                // process client data  
                System.out.println("The content sent by the client: " + clientInputStr);

                // reply message to client  
                DataOutputStream out = new DataOutputStream(socket.getOutputStream());
                System.out.print("Please input:\t");
                // send a line of keyboard input  
                String s = new BufferedReader(new InputStreamReader(System.in)).readLine();
                out.writeUTF(s);

                out.close();
                input.close();
            } catch (Exception e) {
                System.out.println("Server run exception: " + e.getMessage());
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (Exception e) {
                        socket = null;
                        System.out.println("Server finally exception:" + e.getMessage());
                    }
                }
            }
        }
    }
}  

1.3 After configuring Tomcat in the first step of environment configuration, click the Tomcat icon in Eclipse to run Tomcat

1.4 Right-click on the Main class to Run as-->Java Application service to run

2. Client      

Create a new Android project, write the following code in MainActivity, pay attention to modify the address of your IP:

package com.example.zgp.chatfree;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;


public class MainActivity extends ActionBarActivity {
    private TextView myTextView;
    private Button mBtnConnect;

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

        myTextView = (TextView) findViewById(R.id.tv_info);
        mBtnConnect=(Button)findViewById(R.id.btn_connect);
        mBtnConnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new Thread(new Runnable() {
                    @Override
                    public void run() {

                            Socket socket = null;
                            try {
                                //Create a stream socket and connect it to the specified port number on the specified host
                                socket = new Socket("192.168.1.91", 8888);

                                //read server-side data
                                DataInputStream input = new DataInputStream(socket.getInputStream());
                                // send data to the server
                                DataOutputStream out = new DataOutputStream(socket.getOutputStream());
                                String str = "I am Client";
                                out.writeUTF(str);

                                final String ret = input.readUTF();
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        myTextView.setText(ret);
                                        Toast.makeText(MainActivity.this,ret,Toast.LENGTH_SHORT).show();
                                    }
                                });
                                System.out.println("The server returned: " + ret);


                                out.close();
                                input.close();
                            } catch (Exception e) {
                                System.out.println("Client exception:" + e.getMessage());
                            } finally {
                                if (socket != null) {
                                    try {
                                        socket.close();
                                    } catch (IOException e) {
                                        socket = null;
                                        System.out.println("Client finally exception: " + e.getMessage());
                                    }
                                }
                            }
                        }

                }).start();


            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiedIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

The layout file is as follows:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv_info"
        android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
   <Button
       android:layout_below="@+id/tv_info"
       android:text="Connect"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:id="@+id/btn_connect"/>
</RelativeLayout>

Run the Android project, click the Button above, you can see the output in the Eclipse server console, and you can see the changes in the text box in the app by entering characters in the console.




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324686292&siteId=291194637