1

我正在开发一个通过套接字连接到服务器的 android Quiz 应用程序。在客户端(Android 设备)上,我在 while 循环中检查服务器(Java 服务器)给出的答案。连接和答案的接收一切顺利。问题是在我的课堂上检查答案有一个错误。为了提供更多信息,我将在此处包含部分代码:

public void startClient(){

    checkValue = new Thread(new Runnable(){
        @Override
        public void run() {     
            try
            {
                final int PORT = 4444;
                final String HOST = "192.168.1.118";
                Socket SOCK = new Socket(HOST, PORT);
                Log.e("success", "You connected to: " + HOST);

                quizClient = new QuizClient(SOCK);

                //Send the groupname to the list
                PrintWriter OUT = new PrintWriter(SOCK.getOutputStream());
                OUT.println(groupName);
                OUT.flush();

                Thread X = new Thread(quizClient);
                X.start();

                connected = true;


            }
            catch(Exception X)
            {
                Log.e("connection error", "Error: ", X);
            }       
        }
    });

    checkValue.start(); 

}

public void testvalue(){

    Thread thread = new Thread(new Runnable(){
        @Override
        public void run() {
            try {
                while(true){
                    if(message != null && !message.matches("")){
                        Thread.sleep(1000);
                        Log.e("receive", message);
                        buffer = message;
                        message = "";

                        Message msg = new Message();
                        String textTochange = buffer;
                        msg.obj = textTochange;
                        mHandler.sendMessage(msg);
                        Thread.sleep(3000);
                    }

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

    thread.start();

}

Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {

        String text = (String)msg.obj;
        //call setText here

        //String[] myStringArray = new String[]; 
        value.clear();

        String[] items = text.split(";");
        for (String item : items)
        {
            value.add(item);
            Log.e("message", item);
            //System.out.println("item = " + item);
        }

        if(value.get(0).equals("1")){

            questionGroup.setVisibility(View.INVISIBLE);
            sendAnswer.setVisibility(View.INVISIBLE);
            answer.setVisibility(View.INVISIBLE);
            question.setText("");


            question.setText(value.get(2));
            rad1.setText(value.get(3));
            rad2.setText(value.get(4));
            rad3.setText(value.get(5));
            rad4.setText(value.get(6));

            questionGroup.setVisibility(View.VISIBLE);
            sendAnswer.setVisibility(View.VISIBLE);


        } else if (value.get(0).equals("2")){

            questionGroup.setVisibility(View.INVISIBLE);
            sendAnswer.setVisibility(View.INVISIBLE);
            answer.setVisibility(View.INVISIBLE);

            question.setText("");
            question.setText(value.get(2));
            answer.setVisibility(View.VISIBLE);
            sendAnswer.setVisibility(View.VISIBLE);


        } else
        {
            questionGroup.setVisibility(View.INVISIBLE);
            sendAnswer.setVisibility(View.INVISIBLE);
            answer.setVisibility(View.INVISIBLE);

            question.setText(text);
        }


    }
};

@Override
protected void onStop() 
{

    if (connected == true){
        try {
            quizClient.DISCONNECT();
        } catch (IOException e) {
            e.printStackTrace();
        }   
    }

    if(checkValue != null)
    {
        checkValue.interrupt();
    }

    super.onStop();
    closeApplication();

}

所以我创建了这个类的一个新实例(我实际上检查传入的数据流)

public class QuizClient implements Runnable {

//Globals 
Socket SOCK;
Scanner INPUT;
Scanner SEND = new Scanner(System.in);
PrintWriter OUT;

public QuizClient(Socket X)
{
    this.SOCK = X;
}

public void run()
{
    try
    {
        try
        {
            INPUT = new Scanner(SOCK.getInputStream());
            OUT = new PrintWriter(SOCK.getOutputStream());
            OUT.flush();
            CheckStream();
        }
        finally
        {
            SOCK.close();
        }
    }
    catch(Exception X)
    {
        Log.e("error", "error: ", X);
    }
}

public void DISCONNECT() throws IOException
{
    OUT.println("DISCONNECT");
    OUT.flush();
    SOCK.close();
}

public void CheckStream()
{
    while(true)
    {
        RECEIVE();
    }
}

public void RECEIVE()
{

    if(INPUT.hasNext())
    {
        String MESSAGE = INPUT.nextLine();

        if(MESSAGE.contains("#?!"))
        {

        }
        else
        {
            QuizActivity.message = MESSAGE;
            Log.e("test", MESSAGE);
        }
    }
}

public void SEND(String X)
{
    OUT.println(X);
    OUT.flush();
}
}

所以我认为在下面的课程中这个错误仍然存​​在:

public void testvalue(){

    Thread thread = new Thread(new Runnable(){
        @Override
        public void run() {
            try {
                while(true){
                    if(message != null && !message.matches("")){
                        Thread.sleep(1000);
                        Log.e("receive", message);
                        buffer = message;
                        message = "";

我在这里做的是创建一个线程并检查“消息”是否不等于 null。消息来自另一个类:

public void RECEIVE()
{

    if(INPUT.hasNext())
    {
        String MESSAGE = INPUT.nextLine();

        if(MESSAGE.contains("#?!"))
        {

        }
        else
        {
            QuizActivity.message = MESSAGE;

现在大多数时候这很好用,但有两个问题。当我离开页面时,它与服务器断开连接(工作)我返回页面并再次连接到服务器,但这次我没有在屏幕上获得任何值(接收正常,但对于另一个原因在我的处理程序中效果不佳)。一段时间后还会得到一个 indexoutofboundexception:

question.setText(value.get(2));

第二个问题在程序运行时出现了一段时间。有时我的界面在正确接收输入时也没有得到值。

所以我的猜测是,我对读取值的线程的解决方案并不是处理它的最佳方法。所以现在我问有更多经验的人,我可以做些什么来使这项工作没有重大问题?您需要知道连接是否有效,并且我在 QuizClient 类中获得了值。所以问题需要在我的主要课程中。

我的 oncreate 课程:

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

    selectgroep = (Spinner) findViewById(R.id.groepen);
    questionGroup = (RadioGroup) findViewById(R.id.QuestionGroup);
    sendAnswer = (Button) findViewById(R.id.sendAnswer);

    rad1 = (RadioButton) findViewById(R.id.radio0);
    rad2 = (RadioButton) findViewById(R.id.radio1);
    rad3 = (RadioButton) findViewById(R.id.radio2);
    rad4 = (RadioButton) findViewById(R.id.radio3);

    answer = (EditText) findViewById(R.id.textanswer);

    questionGroup.setVisibility(View.INVISIBLE);
    sendAnswer.setVisibility(View.INVISIBLE);
    answer.setVisibility(View.INVISIBLE);


    try {
        connect();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    //Code na het drukken op de knop
    startserver = (Button) findViewById(R.id.startserver);
    startserver.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            startClient();
            getID();
            testvalue();
        }

});

    sendAnswer.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // Stuur antwoord door en sluit alles af 
            questionGroup.setVisibility(View.INVISIBLE);
            sendAnswer.setVisibility(View.INVISIBLE);
            answer.setVisibility(View.INVISIBLE);
            answer.setText("");

            rad1.setChecked(true);
            rad1.setText("");
            rad2.setText("");
            rad3.setText("");
            rad4.setText("");

            question.setText("Wachten op server ... ");

        }
    });

}

提前谢谢你,托马斯·索夫特

4

0 回答 0