繁体   English   中英

无法为一个Java服务器管理多个客户端(Android设备)

[英]Unable to manage multiple clients (android devices) for a single java server

我需要服务器来跟踪每个客户端的连接。 建议我使用线程。 所以我想要实现的是为每个客户端创建一个线程,该线程应运行到客户端连接存在为止。 但是发生的是,对于任何客户端发送的每条消息,都在doInBackground()函数中创建了一个新的客户端连接。 因此,我没有为一个客户端使用一个线程,而是为发送到服务器的任何客户端消息使用了一个线程。 您能否提出一种方法,使我的服务器能够区分来自不同客户端的不同消息?

Java服务器代码:

package com.nss.academyassistserver;

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

public class AcademyAssistServer {
    public static ServerSocket serverSocket;
    public static Socket clientSocket;

    static final int PORT = 4444;

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            serverSocket = new ServerSocket(PORT); // Server socket         
        } catch (IOException e) {
            System.out.println("Could not listen on port: "+PORT+" \n");
        }
        System.out.println("Server started. Listening to the port "+PORT);

        while (true) {
            try {
                clientSocket = serverSocket.accept();
                System.out.println("New connection accepted."); // accept the client connection
            } catch (IOException ex) {
                System.out.println("Problem in message reading");
            }
            //new thread for a client               
            new EchoThread(clientSocket).start();
        }
    }
}

class EchoThread extends Thread {

    InputStreamReader inputStreamReader;
    BufferedReader bufferedReader;
    String fromClient;
    Socket clientSocket;

    public EchoThread(Socket clientSocket) {
        this.clientSocket = clientSocket;
    }

    public void run() {
        try {
            inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
            bufferedReader = new BufferedReader(inputStreamReader); // get the client message
        } catch (IOException e) {
            return;
        }

        while (!Thread.currentThread().isInterrupted()) {
             System.out.println("I am thread " + Thread.currentThread().getId()); 
            try {
                fromClient = bufferedReader.readLine();
                if ((fromClient == null) || fromClient.equalsIgnoreCase("exit")) {
                    System.out.println("You're welcome, bye!");

                    return;
                } else {
                    System.out.println(fromClient);
                    Thread.currentThread().interrupt();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
        }
        try {
            clientSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

客户活动代码:

    package com.nss.academyassist;

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Locale;

    //import statements for client
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.net.Socket;
    import java.net.UnknownHostException;

    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.view.Window;
    import android.view.WindowManager;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ImageButton;
    import android.widget.Toast;

    //import statements for client
    import android.os.AsyncTask;


    public class MainActivity extends Activity implements OnClickListener {

        EditText question;

        //Client sockets
        private Socket client;
        private PrintWriter printwriter;
        private String toTag;

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

            question = (EditText)findViewById(R.id.editText1);

            Button query = (Button)findViewById(R.id.button2);
            query.setOnClickListener(this);
        }

        private class SendMessage extends AsyncTask<Void, Void, Void> {

            @Override
            protected Void doInBackground(Void... params) {

                try {
                    client = new Socket("Server IP Address", 4444);
                    printwriter = new PrintWriter(client.getOutputStream(), true);
                    printwriter.write(toTag); // write the message to output stream

                    printwriter.flush();
                    printwriter.close();
                    client.close(); // closing the connection

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

        public void onClick(View v)
        {
            switch(v.getId())
            {
                case R.id.button2:

                        toTag = question.getText().toString();
                        // Output the result
                        Toast.makeText(getApplicationContext(), toTag, 
                                       Toast.LENGTH_LONG).show();

                        //Invoke the execute method of AsynTask, which will run the doInBackground method of SendMessage Class
                        SendMessage sendMessageTask = new SendMessage();
                        sendMessageTask.execute();

                    break;
            }

        }
}

您可以使用IP告诉客户端。 采用

clientSocket.getInetAddress().getHostAddress()

您还可以在android代码中保持客户端未关闭。 例如,您可以在onCreate打开Socket并在onDestroy中将其close

问题的原因在于您的客户端代码。 使用new Socket(..)客户端每次向服务器发送标签时都会创建一个新的连接。 因此,您可以创建一个可以重用的连接:

public class MainActivity extends Activity implements OnClickListener {

    /* .. your other variables .. */

    private Socket client;
    private PrintWriter printwriter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        /* .. no change here .. */
    }

    public void onStart()
    {
        if(this.client != null)
        {
            try {
                client = new Socket("Server IP Address", 4444);
                printwriter = new PrintWriter(client.getOutputStream(), true);
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void onClose()
    {
        this.printwriter.close();
        this.printwriter = null;
        this.client.close();
        this.client = null;
    }

    private class SendMessage extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            try {
                printwriter.write(toTag); // write the message to output stream
                printwriter.write("\n"); // delimiter
                printwriter.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    public void onClick(View v)
    {
        switch(v.getId())
        {
            case R.id.button2:

                    toTag = question.getText().toString();
                    // Output the result
                    Toast.makeText(getApplicationContext(), toTag, 
                                   Toast.LENGTH_LONG).show();

                    //Invoke the execute method of AsynTask, which will run the doInBackground method of SendMessage Class
                    SendMessage sendMessageTask = new SendMessage();
                    sendMessageTask.execute();

                break;
        }

    }
}

除此之外,您还应该在标签/消息中附加一些定界符,以便服务器能够将内容与其他消息区分开。

由于您正在使用BufferedReader.readLine()分隔行

由换行符('\\ n'),回车符('\\ r')或回车符中的任意一个后跟换行符

为此,我在上面的示例中添加了一行,该行在该标记之后附加一个换行符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM