我的Android多线程服务器无法正常工作

时间:2014-06-21 12:24:20

标签: android

我试图在我的Android设备上设置分数更新服务器。其他手机可以发送分数,此服务器需要通过更新每个客户端的分数来显示视觉结果。像这样:

enter image description here

现在我的问题是:

1-当前的多线程方法不起作用。这有什么问题?

2-当我收到人们时,我如何区分他们?也许通过使用键值/ hashmap,并更新与每个IP /套接字相对应的分数?

package course.examples.Sensors.ShowValues;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class test extends Activity{
    // Start with some variables
    int i = 0;
    int people = 0;
    ArrayList<Bar> diagrams;

    private static ServerSocket serverSocket;
    private static Socket clientSocket;
    private static InputStreamReader inputStreamReader;
    private static BufferedReader bufferedReader;
    private static String message;
    private static HashMap<String, Integer> map;
    boolean isDone=false;
    private TextView mXValueView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // set orientation
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        mXValueView = (TextView) findViewById(R.id.textView1);

        map= new HashMap<String, Integer>();
        diagrams=new ArrayList<Bar>();
        // In onCreate method
        //      diagrams = new ArrayList<Bar>();
        // draw(0,0);
        //              connect_draw();

        new Thread(new Runnable() {
            public void run() {
                connect_draw();
            }
        }).start();

    }

    // Register listener
    @Override
    protected void onResume() {
        super.onResume();
    }

    // Unregister listener
    @Override
    protected void onPause() {
        super.onPause();
    }


    //  void draw() {
    //      Bar d = new Bar();
    //      d.setColor(Color.parseColor("#118800"));
    //      d.setName("Test1");
    //      d.setValue(i);
    //      Bar d2 = new Bar();
    //      d2.setColor(Color.parseColor("#FFBB33"));
    //      d2.setName("Test2");
    //      d2.setValue(20);
    //      diagrams.add(d);
    //      diagrams.add(d2);
    //      BarGraph g = (BarGraph) findViewById(R.id.graph);
    //      g.setBars(diagrams);
    //  }

    void draw(int hash, int score){
        //the person was not existed: Create a new Bar
        if(!map.containsKey(hash) ){
            Bar d = new Bar();
            d.setColor(Color.rgb(new Random().nextInt(255), new Random().nextInt(255), new Random().nextInt(255)));
            d.setName(people++ +"");
            d.setValue((float)score);
            diagrams.add(d);
        }

        BarGraph g = (BarGraph)findViewById(R.id.graph);
        g.setBars(diagrams);
    }

    void connect_draw() {
        try {
            serverSocket = new ServerSocket(8888); // Server socket
            Log.i("hello","hello: Server started. Listening to the port 8888");

            isDone=true;
            while (true) {
                clientSocket = serverSocket.accept(); // accept the client
                // connection
                inputStreamReader = new InputStreamReader(
                        clientSocket.getInputStream());
                bufferedReader = new BufferedReader(inputStreamReader); // get the client message
                message = bufferedReader.readLine();
                final int hash=clientSocket.getInetAddress().hashCode();
                //              i++;

                // draw(hash,Integer.parseInt(message));
                mXValueView.setText(message);
                Log.i("hello","hello: server received "+message+ " from "+hash);
                inputStreamReader.close();
                clientSocket.close();
            }
        }catch (IOException ex) {
            Log.e("hello","hello: problem in reading message");
        }
    }

}

这是客户端代码:

package com.lakj.comspace.simpletextclient;

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

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class SlimpleTextClientActivity extends Activity {

    private Socket client;
    private PrintWriter printwriter;
    private EditText textField;
    private Button button;
    private String messsage;

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

        textField = (EditText) findViewById(R.id.editText1); // reference to the text field
        button = (Button) findViewById(R.id.button1); // reference to the send button

        // Button press event listener
        button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                messsage = textField.getText().toString(); // get the text message on the text field
                textField.setText(""); // Reset the text field to blank
                SendMessage sendMessageTask = new SendMessage();
                sendMessageTask.execute();
            }
        });
    }

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

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

//10.73.172.214
                client = new Socket("10.73.172.214", 8888); // connect to the server
                printwriter = new PrintWriter(client.getOutputStream(), true);
                printwriter.write(messsage); // 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;
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.slimple_text_client, menu);
        return true;
    }

}

更新:我刚刚添加了一个简单的textView,并注意到我实际上没有在另一个线程上更新UI视图。我该怎么办?这是警告的内容。

06-21 14:44:31.871: E/ACDB-LOADER(257): Error: ACDB audproc returned = -8
06-21 14:44:31.871: E/ACDB-LOADER(257): Error: ACDB AudProc vol returned = -8
06-21 14:44:31.951: W/InputMethodManagerService(575): Starting input on non-focused client com.android.internal.view.IInputMethodClient$Stub$Proxy@41e1aff0 (uid=10043 pid=2841)
06-21 14:44:35.004: E/ALSADevice(257): standby handle h 0x41597050
06-21 14:44:35.054: E/ALSADevice(257): Number of modifiers 0
06-21 14:44:35.054: E/ALSADevice(257): usecase_type is 0
06-21 14:44:35.895: W/ActivityManager(575): No content provider found for permission revoke: file:///data/local/tmp/test.apk
06-21 14:44:35.895: W/ActivityManager(575): No content provider found for permission revoke: file:///data/local/tmp/test.apk
06-21 14:44:36.115: W/PackageManager(575): Code path for pkg : course.examples.Sensors.ShowValues changing from /data/app/course.examples.Sensors.ShowValues-1.apk to /data/app/course.examples.Sensors.ShowValues-2.apk
06-21 14:44:36.115: W/PackageManager(575): Resource path for pkg : course.examples.Sensors.ShowValues changing from /data/app/course.examples.Sensors.ShowValues-1.apk to /data/app/course.examples.Sensors.ShowValues-2.apk
06-21 14:44:36.315: W/ResourceType(575): Failure getting entry for 0x7f060000 (t=5 e=0) in package 0 (error -75)
06-21 14:44:36.315: W/ResourceType(575): Failure getting entry for 0x7f060000 (t=5 e=0) in package 0 (error -75)
06-21 14:44:36.315: W/InputMethodManagerService(575): Found no subtypes in a system IME: com.android.inputmethod.pinyin
06-21 14:44:36.365: W/RecognitionManagerService(575): no available voice recognition services found
06-21 14:44:36.796: W/ProcessStats(575): Skipping unknown process pid 2918
06-21 14:44:36.806: W/ProcessStats(575): Skipping unknown process pid 2923
06-21 14:44:36.806: W/ProcessStats(575): Skipping unknown process pid 2929
06-21 14:44:36.806: W/ProcessStats(575): Skipping unknown process pid 2933
06-21 14:44:37.216: E/Trace(2953): error opening trace file: No such file or directory (2)
06-21 14:44:37.356: E/hello(2953): hello: problem in reading message
06-21 14:44:37.406: E/BufferQueue(254): [Starting course.examples.Sensors.ShowValues] drainQueueLocked: BufferQueue has been abandoned!
06-21 14:44:37.486: W/IInputConnectionWrapper(869): showStatusIcon on inactive InputConnection
06-21 14:44:56.447: W/CNE(575): UNKOWN Unsolicited Event 5
06-21 14:44:59.410: E/StatusBar.NetworkController(662): updateDataNetType NETWORK_TYPE_UNKNOWN
06-21 14:44:59.450: E/StatusBar.NetworkController(662): updateDataNetType NETWORK_TYPE_UNKNOWN

1 个答案:

答案 0 :(得分:0)

我们无法看到您的客户发送的内容。我们看到您的服务器读取一行然后关闭客户端。然后服务器递增变量i。服务器对接收到的行中的信息不执行任何操作。每个客户都应该在该行中放置一个标识符,然后是分数。然后,服务器将解码该行的标识符和分数。您正在显示图表但不是您的图表?