0

接続されているすべてのクライアントに受信した入力を送り返すサーバーを作成しようとしています。作成時にスレッドを開始するサービスを使用しています。

public void onCreate() 
{       
    Thread fst = new Thread(new ServerThread());
    fst.start();
}

ここにスレッドがあります

 public void run() 
        {
        try 
            {                                           
                        serverSocket = new ServerSocket(SERVERPORT);
            while (true) 
                {
                    // listen for incoming clients
                    Socket client = serverSocket.accept();
                    mclients = new Vector<Socket>();
                    mclients.add(client);
                    boolean finished = false;   
                    try                             
                        {
                        for(int i=0; i<mclients.size(); i++)        {
                            DataInputStream in = new DataInputStream(mclients.get(i).getInputStream());
                            PrintStream out = new PrintStream(mclients.get(i).getOutputStream());
                            // Print a message:
                            System.out.println("Client from : " + mclients.get(i).getInetAddress() + " port " + mclients.get(i).getPort());
                            // now get the input from the socket...
                            while(!finished) 
                            {
                                String st = in.readLine();
                                // Send the same back to client
                                out.println(st);
                                // Write it to the screen as well
                                System.out.println(st);
                                // If the input was "quit" then exit...
                                if (st.equals("quit")) { finished = true; System.out.println("Thread exiting..."); }
                            }
                                                                    }
                                handler.post(new Runnable() {@Override public void run() {}});                                  

                        }
                    catch (final Exception e) {handler.post(new Runnable() {@Override public void run() {}});e.printStackTrace();}
                }

入力を送信したクライアントに対してのみ機能します。入力はすべてのクライアントにエコーバックされません.誰かがこれを手伝ってくれますか.私のクライアントコードが間違っていると思いますが、それを理解することはできません.これが私のクライアントコードです:

public class Client extends Activity implements OnClickListener{

private EditText serverIp;
private static EditText data;
private TextView receivedata, answer1 ,answer2, answer3, answer4;
private Button connectPhones, send;
private String serverIpAddress = "";
private boolean connected = false;

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


    serverIp = (EditText) findViewById(R.id.server_ip);
    receivedata = (TextView) findViewById(R.id.textView1);
    answer1 = (TextView) findViewById(R.id.txtans1);
    answer2 = (TextView) findViewById(R.id.txtans2);
    answer3 = (TextView) findViewById(R.id.txtans3);
    answer4 = (TextView) findViewById(R.id.txtans4);
    data = (EditText) findViewById(R.id.data);
    connectPhones = (Button) findViewById(R.id.connect_phones);
    send = (Button) findViewById(R.id.send);
    connectPhones.setOnClickListener(this);
    send.setOnClickListener(this);
}


    @Override
    public void onClick(View v) {        
        if(v == send)
        {
            if (!connected)
            {
                serverIpAddress = serverIp.getText().toString();
                if (!serverIpAddress.equals("")) 
                {
                    Thread cThread = new Thread(new ClientThread());
                    cThread.start();
                }
            }
        }
                                }  
    public class ClientThread implements Runnable 
    {           
        String line;
        String[] answers = new String[5];
            final Handler handler = new Handler();
            final Runnable updateUI = new Runnable()    {
                public void run()   {
                   receivedata.setText( line );
                   //answer1.setText( answers[1] ); 
                   //answer2.setText( answers[2] ); 
                   //answer3.setText( answers[3] ); 
                   //answer4.setText( answers[4] ); 
                                    }
                                                        };
        public void run() 
        {
            try 
            {
                InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
                Log.d("ClientActivity", "C: SENDING...");
                Socket socket = new Socket(serverAddr, 5000);
                connected = true;
                while(connected) 
                {
                    try 
                    {                           
                    BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream()));                        
                    PrintStream out = new PrintStream(socket.getOutputStream());                                            
                    out.println(data.getText());                                 
                    line = in.readLine();       // read server
                    System.out.println("Echo: " + line);                        
                    handler.post(updateUI);
                    in.close();                     // Close stream
                    out.close();
                    }                       
                    catch (Exception e) 
                        {
                            Log.e("ClientActivity", "S: Error", e);                             
                        }                                       
                        connected = false;
                }
                            Log.d("ClientActivity", "C: Closed.");
            }   catch (Exception e)
                        {
                            Log.e("ClientActivity", "C: Error", e);

                        }
        }        
        }}

-----編集------
クライアントの処理に別のスレッドを使用する必要がありますか?それとも問題になりますか? そして、どうすればいいですか?

4

2 に答える 2

0

簡単に(非常に簡単に)見てみると、あなたの問題はrun()内の次のコードにあると思われます

mclients = new Vector();

プログラムを実行するたびに新しいベクトル オブジェクトを作成しています。

これを run() の外に移動し、着信接続をリッスンするスレッドを開始する前に mClients が作成されていることを確認することをお勧めします。

ただし、Android フォンでサーバーを実行することはお勧めできません。携帯電話には、限られたバッテリ寿命、処理、メモリ、一貫性のないインターネット接続などの制限があります。このような通信を処理する方法は他にもあります。たとえば、メッセージング、c2dm、xmpp などを検討してください。

于 2012-05-14T15:41:12.190 に答える