0

我正在尝试制作客户端服务器应用程序。我已经做了孔连接,它工作正常。我的服务器运行我的 PC 和我的客户端到我的 android 手机。我想从客户端向服务器发送和接收对象,我已经让服务器发送对象但我不知道如何在我的客户端中接收它们。我的对象类是 PacketManager。

公共类 PacketManager 实现 Serializable {

public String choise; 
public int amount; 

//Constructor
PacketManager(String ep,int p){
    choise=ep;
    amount=p;
}

}

我的 MainActivity :

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);

        arrayList = new ArrayList<String>();

        mList = (ListView)findViewById(R.id.list);
        mAdapter = new MyCustomAdapter(this, arrayList);
        mList.setAdapter(mAdapter);

        // connect to the server
        new connectTask().execute("");
    }

    public class connectTask extends AsyncTask<String,String,TCPClient> {

        @Override
        protected TCPClient doInBackground(String... message) {

            //we create a TCPClient object and
            mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
                @Override
                //here the messageReceived method is implemented
                public void messageReceived(String message) {
                    //this method calls the onProgressUpdate
                    publishProgress(message);
                }
            });
            mTcpClient.run();

            return null;
        }

        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);

            //in the arrayList we add the messaged received from server
            arrayList.add(values[0]);
            // notify the adapter that the data set has changed. This means that new message received
            // from server was added to the list
            mAdapter.notifyDataSetChanged();
        }
    }
}

最后我的客户类:

PrintWriter 输出;BufferedReader 中;

public TCPClient(OnMessageReceived listener) {
    mMessageListener = listener;
} 
/**
 * Sends the message entered by client to the server
 * @param message text entered by client
 */
public void sendMessage(String message){
    if (out != null && !out.checkError()) {
        out.println(message);
        out.flush();
    }
}
public void stopClient(){
    mRun = false;
}

public void run() {

    mRun = true;

    try {
        //here you must put your computer's IP address.
        InetAddress serverAddr = InetAddress.getByName(SERVERIP);

        Log.e("TCP Client", "C: Connecting...");

        //create a socket to make the connection with the server
        Socket socket = new Socket(serverAddr, SERVERPORT);

        try {
            //send the message to the server
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

            Log.e("TCP Client", "C: Sent.");

            Log.e("TCP Client", "C: Done.");

            //receive the message which the server sends back
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            //in this while the client listens for the messages sent by the server
            while (mRun) {
                serverMessage = in.readLine();

                if (serverMessage != null && mMessageListener != null) {
                    //call the method messageReceived from MyActivity class
                    mMessageListener.messageReceived(serverMessage);
                }
                serverMessage = null;

            }


            Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");


        } catch (Exception e) {

            Log.e("TCP", "S: Error", e);

        } finally {
            //the socket must be closed. It is not possible to reconnect to this socket
            // after it is closed, which means a new socket instance has to be created.
            socket.close();
        }

    } catch (Exception e) {
        Log.e("TCP", "C: Error", e);
    }
}
//Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
//class at on asynckTask doInBackground
public interface OnMessageReceived {
    public void messageReceived(String message);
}

}

任何人都可以帮我解决这个问题吗,阿拉连接工作正常,但我想从服务器接收 Pack 对象,但我不知道怎么做。我尝试将 public void messageReceived(String message) 的类型更改为 public void messageReceived(PackageManager Pack) 但后来我遇到了 protected TCPClient doInBackground(String... message) 和 protected void onProgressUpdate(String... values) 的问题.

服务器代码

enter code here public TCPServer(OnMessageReceived messageListener) {
    this.messageListener = messageListener;
public void sendMessage(String message) throws IOException{
    if (mOut != null && !mOut.checkError()) {
        mOut.println(message);     
        mOut.flush();
    }
}@Override
public void run() {
    super.run();
    running = true;try {System.out.println("S: Connecting...");
        //create a server socket. A server socket waits for requests to come in over the network.
        ServerSocket serverSocket = new ServerSocket(SERVERPORT);
        //create client socket... the method accept() listens for a connection to be made to this socket and accepts it.
        Socket client = serverSocket.accept();
        System.out.println("S: Receiving...");
        try {//sends the message to the client
            mOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);  
            //read the message received from client
            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            //in this while we wait to receive messages from client (it's an infinite loop)
            //this while it's like a listener for messages
            while (running) {
                String message = in.readLine();
                if (message != null && messageListener != null) {
                    //call the method messageReceived from ServerBoard class
                    messageListener.messageReceived(message);
                }
            }catch (Exception e) {
            System.out.println("S: Error");
            e.printStackTrace();
        } finally {
            client.close();
            System.out.println("S: Done.");
        }
    } catch (Exception e) {
        System.out.println("S: Error");
        e.printStackTrace();
    }
} 
//Declare the interface. The method messageReceived(String message) will must be implemented in the ServerBoard
//class at on startServer button click
public interface OnMessageReceived {
    public void messageReceived(String message);
}
4

0 回答 0