【问题标题】:How to add Client-Server to Android app activites如何将客户端服务器添加到 Android 应用程序活动
【发布时间】:2018-02-20 18:05:32
【问题描述】:

所以我正在 Android Studio 中构建一个移动应用程序。该应用程序允许不同设备上的多个用户可以登录他们的帐户。我想要实现的功能之一是在线用户之间的实时聊天。

我在 Eclipse 中完成了这项工作,在本地网络上使用客户端-服务器模型。服务器设置一个套接字,该套接字是线程化的,因此多个客户端可以连接和聊天。这在使用 Java swing 的 Eclipse 中工作,这很容易,因为与服务器通信和更新 UI 都在一个类中完成。

然而,我对 Android 开发相对较新,并且正在努力让它工作,因为客户端和服务器之间的通信可以通过 Activity 显示在 UI 上。

谁能解释一下您如何在活动和我的客户类之间建立联系?下面我放了我的 Server、ServerThreads 和 Client 类,它们(通过终端)可以正确通信。

服务器:

package com.degree.abbylaura.demothree.Server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {


 public static void main(String args[]) throws IOException {

    //create a server and client sockets
    ServerSocket serverSocket = null;
    Socket clientSocket = null;

    int portNumber = 8888; //TO BE CHANGED


    //setup server socket
    try{
        serverSocket = new ServerSocket(portNumber);
        System.out.println("Socket set up");

        //in true loop listen forever for incoming connections
        //allows multiple clients to be handled
        while(true) {

            //accept connection with clients socket
            //open reader and writer for communication
            try {

                //connection accepted
                clientSocket = serverSocket.accept();
                System.out.println("client accepted");

                //create a new multi-server-thread object to handle new client
                //pass it the socket returned from the accept and start the thread
                new ServerThreads(clientSocket).start();


                //carry on listening for new connections forever

            } catch (IOException e) {
                System.err.println("IO error " + e.getMessage());
            }

        }
    } catch (IOException e) {
        System.out.println(e);
    } finally {
        try{
            serverSocket.close();
        } catch (IOException e){
            System.out.println(e);
        }

    }


 }
}

服务器线程:

package com.degree.abbylaura.demothree.Server;

import com.degree.abbylaura.demothree.Server.ServerRequests;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ServerThreads extends Thread{

  private Socket clientSocket;

  public ServerThreads(Socket clientSocket){
    super();
    this.clientSocket = clientSocket;
  }

  public void run(){

    try {
        BufferedReader inFromClient = new BufferedReader(
                new InputStreamReader(clientSocket.getInputStream()));

        PrintWriter outToClient =
                new PrintWriter(clientSocket.getOutputStream(), true);


        Boolean communicating = true;
        String response = null;

        String myresponse = "FIRST TO CLIENT"; //debugging


        while(communicating){

            outToClient.println("FIRST TO CLIENT");
            response = inFromClient.readLine();
            System.out.println(myresponse + " : " + response);


            if(response.equals("FIRST TO SERVER")){
                myresponse = "SECOND TO CLIENT";
                outToClient.println("SECOND TO CLIENT");

            }else if(response.equals("SECOND TO SERVER")){
                myresponse = "SERVER ENDING COMMUNICATION";
                outToClient.println("SERVER ENDING COMMUNICATION");

            }else if(response.equals("CLIENT END")){
                communicating = false;
            }

        }

        clientSocket.close();
        return;



    } catch (IOException e) {
        e.printStackTrace();


    } finally {
        try{
            clientSocket.close();
        }

        catch (IOException e){
            e.printStackTrace();
        }
    }




  }
}

客户:

package com.degree.abbylaura.demothree.Client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {

  public static void main(String args[]){
    String hostName = "localhost";
    int portNumber = 8888; //TO CHANGE

    ClientHandler handler = new ClientHandler();

    //create client socket
    Socket socket = null;
    BufferedReader inFromServer = null;
    PrintWriter outToServer = null;

    try{
        socket = new Socket(hostName, portNumber);
        System.out.println("socket created");

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

        outToServer = new PrintWriter(socket.getOutputStream(), true);


        Boolean communicating = true;
        String response = null;
        String myresponse = null;


        while(communicating){

            response = inFromServer.readLine();
            System.out.println(myresponse + " : " + response);


            if(response.equals("FIRST TO CLIENT")){
                myresponse = "FIRST TO SERVER";

                outToServer.println("FIRST TO SERVER");

            }else if(response.equals("SECOND TO CLIENT")){
                myresponse = "SECOND TO SERVER";

                outToServer.println("SECOND TO SERVER");

            }else if(response.equals("SERVER ENDING COMMUNICATION")){
                myresponse = "CLIENT END";

                outToServer.println("CLIENT END");
                communicating = false; //may or may not need this line in
            }


        }


    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

  }


}

【问题讨论】:

    标签: android android-studio server client client-server


    【解决方案1】:

    1) 你可以从学习这个例子开始

    https://github.com/schwiz/android-websocket-example

    https://github.com/schwiz/websocket-server

    (服务器端与语言无关 - 因为我们在这里使用套接字,所以可以是 c 或 java 实现或任何其他)

    2) 基本上您需要熟悉“android api”方面,例如:

     a. Service class
       (to maintain communication with server/ do job outside main aka ui thread)
     + Binder class :) functionality
       (allowing Activity and Service  to communicate with each other) 
     + ServiceConnection class 
       (to bind from Activity to Service to use Binder*) 
    
     b. wakelocks
       (for above to hold / persist connection)
    
     c. Socket class 
        (to create connection with server and exchange data) 
    

    *binder 是一种 android IPC 机制,类似于您尝试实现的套接字机制(支持 linux 内核构建),主要是出于安全原因,它是 google 的首选 - 如果您的服务是本地服务,您可以跳过关于活页夹事务的部分:) 并更多地关注基于服务的方法的其他方面。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多