Rathohan Wu
Rathohan Wu

Reputation: 13

Android Server And Client Connection

I have been trying to develop an android app which can send an command like 'S','A',or 'B' to other devices like indicators with wi-fi modules. So, I am trying to establish this connection between my android device and wi-fi module by using wi-fi.

I have searched for some information on the android developer web. I don't know why on the edge of the server, I just have to provide information of "port". And on the edge of the client, I have to provide information of "port" and "address".

Upvotes: 1

Views: 482

Answers (2)

John
John

Reputation: 11

Hi I can provide some code that does a simple connect to a server that runs in java using only the console and a basic android application that connects to the server using socket connection. Its just example code that runs on an emulator such as that from eclipse. Really hope it helps. Will provide a better example soon with some steps. As long as the phone is using android of course with sdk version 14 and above. The code isn't really clean, ill also do that later.

MainActivity.java for android side using AsyncTask

    public class MainActivity extends Activity {

    Socket socket = null;
    DataOutputStream output;
    DataInputStream input;
    ObjectInputStream objectInput;
    Button buttonConnect;
    Button createTest;
    TextView textResponse;

    EditText subjectInput, gradeInput, testNameInput;
    String curSubject, curGrade, curName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        buttonConnect = (Button) findViewById(R.id.buttonConnect);
        createTest = (Button) findViewById(R.id.createTest);
        textResponse = (TextView) findViewById(R.id.textResponse);

        buttonConnect.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new ConnectThread().execute("Connect");
                buttonConnect.setText("Connected");
            }
        });
        createTest.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                subjectInput = (EditText) findViewById(R.id.editText1);
                gradeInput = (EditText) findViewById(R.id.editText2);
                testNameInput = (EditText) findViewById(R.id.editText3);
                ConnectThread thread = new ConnectThread(subjectInput.getText()
                        .toString(), gradeInput.getText().toString(),
                        testNameInput.getText().toString());
                thread.execute("createOpen");
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public class ConnectThread extends AsyncTask<String, String, String> {
        String response = "Nothing yet";
        String subject, grade, name;

        public ConnectThread() {
        }

        public ConnectThread(String subject, String grade, String name) {
            this.subject = subject;
            this.grade = grade;
            this.name = name;
        }

        @Override
        protected String doInBackground(String... params) {
            if (params[0].equals("Connect")) {
                connect();
            }
            if (params[0].equals("createOpen")) {
                createOpen();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            textResponse.setText(response);
            super.onPostExecute(result);
        }

        public void createOpen() {
            try {
                output.writeUTF("createOpen");
                output.writeUTF(subject);
                output.writeUTF(grade);
                output.writeUTF(name);
                String command = input.readUTF();
                if (command.equals("null")) {
                    try {
                        Object object = objectInput.readObject();
                        ArrayList<String> curTest = (ArrayList<String>) object;
                        curName = curTest.get(0);
                        curGrade = curTest.get(1);
                        curSubject = curTest.get(2);
                        response = "New Test Created: " + curName;
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                if (command.equals("exists")) {
                    try {
                        Object object = objectInput.readObject();
                        ArrayList<String> curTest = (ArrayList<String>) object;
                        curName = curTest.get(0);
                        curGrade = curTest.get(1);
                        curSubject = curTest.get(2);
                        response = "Test already exists: " + curName;
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public void connect() {
            try {
                socket = new Socket("10.0.0.16", 500);
                output = new DataOutputStream(socket.getOutputStream());
                input = new DataInputStream(socket.getInputStream());
                objectInput = new ObjectInputStream(socket.getInputStream());
                String command = input.readUTF();
                response = command;
            } catch (UnknownHostException e) {
                e.printStackTrace();
                Log.d("fail", e.toString());
                response = "UnknownHostException: " + e.toString();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.d("fail", e.toString());
                response = "IOException: " + e.toString();
            }
        }

        public void disconnect() {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

The Server class for java, which creates the sockets for the client threads

public class Server {
    DataOutputStream os;
    DataInputStream is;
    ArrayList<Test> tests;

    public static void main(String[] args) {
        new Server();
    }

    public void postSystemMessage(String message) {
        System.out.println(message);
    }

    public Server() {
        try {
            tests = new ArrayList<Test>();
            // initial data set up
            System.out.println("Starting server");
            ServerSocket server = new ServerSocket(500, 100);
            System.out.println("Server started");
            System.out.println("----------------------------------");
            while (true) {
                System.out.println("Waiting for connection");
                Socket socket = server.accept();
                ServerThread connection = new ServerThread(socket, this);
                System.out.println("New client connected");
                System.out.println("----------------------------------");
                connection.start();
            }
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName())
                    .log(Level.SEVERE, null, ex);
        }
    }

    public synchronized Test checkifexists(String subject, String grade,
            String name) {
        for (Test test : tests) {
            if (test.getTestName().equals(name)) {
                if (test.getGrade().equals(grade)) {
                    if (test.getSubject().equals(subject)) {
                        return test;
                    }
                }
            }
        }
        return null;
    }

    public synchronized Test createTest(String subject, String grade,
            String name) {
        Test test = new Test(subject, grade, name);
        tests.add(test);
        return test;
    }

    public synchronized void addToTests(Test in) {
        tests.add(in);
    }
}

The server thread class which is set up for multi client connections

public class ServerThread extends Thread {
    private Socket socket;
    private DataInputStream in;
    private DataOutputStream out;
    private ObjectOutputStream objectOutput;
    private Server server;

    public ServerThread(Socket socket, Server server) {
        this.server = server;
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            in = new DataInputStream(socket.getInputStream());
            out = new DataOutputStream(socket.getOutputStream());
            objectOutput = new ObjectOutputStream(socket.getOutputStream());
            out.writeUTF("connection successful");
            String command = "";
            while (!command.equals("quit")) {
                command = in.readUTF();
                if (command.equals("createOpen")) {
                    createOpen();
                } else if (command.equals("getFile")) {
                } else if (command.equals("saveFile")) {
                } else if (command.equals("quit")) {
                    System.out.println("A client has left");
                }
            }
        } catch (IOException e2) {
            System.out.println("Connection dropped");
            e2.printStackTrace();
        } finally {
            try {
                if (in != null)
                    in.close();
                if (out != null)
                    out.close();
                socket.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    public void createOpen() {
        try {
            String subject = in.readUTF();
            String grade = in.readUTF();
            String name = in.readUTF();
            Test curTest = server.checkifexists(subject, grade, name);
            if (curTest == null) {
                Test test = server.createTest(subject, grade, name);
                server.addToTests(test);
                ArrayList<String> toSendTest = new ArrayList<String>();
                toSendTest.add(subject);
                toSendTest.add(grade);
                toSendTest.add(name);
                out.writeUTF("null");
                System.out.println("sending object");
                objectOutput.writeObject(toSendTest);
                objectOutput.flush();
                System.out.println("object sent");
            } else {
                ArrayList<String> toSendTest = new ArrayList<String>();
                toSendTest.add(subject);
                toSendTest.add(grade);
                toSendTest.add(name);
                out.writeUTF("exists");
                System.out.println("sending object");
                objectOutput.writeObject(toSendTest);
                objectOutput.flush();
                System.out.println("object sent");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Upvotes: 1

Roberto Betancourt
Roberto Betancourt

Reputation: 2505

Network Service Discovery may be what you need. What this API does is allow you to broadcast information such as port,IP Address, etc. to other devices in the same network. With that info, you can setup your connections with sockets.

Upvotes: 0

Related Questions