android中的客户端服务器通信,带按钮输入

时间:2014-02-23 11:18:44

标签: android client-server

我是android编程的新手,我正在研究这个代码用于客户端服务器连接。我正在尝试使用按钮将值从客户端发送到服务器。我在互联网上找到了基本客户端服务器连接程序的片段。在程序中,有多个按钮。单击客户端时的按钮应将字符串值传输到服务器。然后服务器应该接收字符串并将其显示在屏幕上。但是当我执行程序时,显示的所有内容都在服务器屏幕上“连接”。我已将按钮f,l,r和b重定向到xml中的buttonPressed()。

这是客户端程序:

    package com.example.androidromo;


    import java.io.BufferedWriter;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.Socket;

    //import com.romotive.demo.R;

    import android.content.Intent;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;

    public class Client_Second extends MainActivityClient {

private EditText serverIp;

private Button connectPhones;

private EditText text;

private Button f, l, r, b;

private String serverIpAddress = "";

private boolean connected = false;



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

      serverIp = (EditText) findViewById(R.id.server_ip);
    connectPhones = (Button) findViewById(R.id.connect_phones);

     /*connectPhones.setOnClickListener(connectListener);
      f= (Button) findViewById(R.id.f);
      f.setOnClickListener(buttonPressed(view));
    */

}

     /*
     private OnClickListener connectListener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        if (!connected) {
            serverIpAddress = serverIp.getText().toString();
            if (!serverIpAddress.equals("")) {
                Thread cThread = new Thread(new ClientThread());
                cThread.start();

            }
        }
    }
};*/

public void buttonPressed(View view)
{
    // Switch on the view's ID:
    String msg=null;
    switch (view.getId())
    {

    case R.id.f:
        msg="f";
        sendMessage(msg);
        break;


    case R.id.l:
        msg="l";
        sendMessage(msg);
        break;


    case R.id.r:
    msg="r";
    sendMessage(msg);
        break;


    case R.id.b:
        msg="b";
        sendMessage(msg);
        break;

}

}

public void sendMessage(String str)
{
final String str1=str;  

if (!connected) {
    serverIpAddress = serverIp.getText().toString();
    if (!serverIpAddress.equals("")) {
        new Thread(new Runnable() {            


    public void run() {
        try {
            InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
            Log.d("Client_Second", "C: Connecting...");
  //          clientStatus.setText("Connecting...");
            Socket socket = new Socket(serverAddr, Server_Second.SERVERPORT);
            connected = true;
            while (connected) {
                try {

                    Log.d("Client_Second", "C: Sending command.");
                    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
                                .getOutputStream())), true);
                        // WHERE YOU ISSUE THE COMMANDS
                      // buttonPressed(f); 
                    //out.println("Hey server");
                    out.println(str1);
                        out.flush();

                        Log.d("Client_Second", "C: Sent.");
                } catch (Exception e) {
                    Log.e("Client_Second", "S: Error", e);
                }
            }
            //socket.close();
            //Log.d("Client_Second", "C: Closed.");
        } catch (Exception e) {
            Log.e("Client_Second", "C: Error", e);
            connected = false;
        }
    }
}).start();
}
}
}
}

服务器代码如下:

 package com.example.androidromo;

 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStreamReader;
 import java.net.InetAddress;
 import java.net.NetworkInterface;
 import java.net.ServerSocket;
 import java.net.Socket;
 import java.net.SocketException;
 import java.util.Enumeration;

 import android.content.Context;
 import android.content.Intent;
 import android.os.Bundle;
 import android.os.Handler;
 import android.util.Log;
 import android.view.View;
 import android.widget.Button;
 import android.widget.TextView;

 public class Server_Second extends MainActivityServer {

 private TextView serverStatus;

 // DEFAULT IP
 public static String SERVERIP = "10.0.2.15";

 // DESIGNATE A PORT
 public static final int SERVERPORT = 8080;

 private Handler handler = new Handler();

 private ServerSocket serverSocket;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.server_second);
     addListenerButton();
     serverStatus = (TextView) findViewById(R.id.server_status);
     SERVERIP = getLocalIpAddress();
  }

private void addListenerButton() {
    // TODO Auto-generated method stub
    final Context context = this;
    Button button = (Button) findViewById(R.id.button11);
    //button.setOnClickListener(new View.OnClickListener() {

        //@Override
        /*public void onClick(View arg0) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(context,Server_Third.class);
            startActivity(intent);
        }*/
    //});
    Button button1 = (Button) findViewById(R.id.preceed);
    button1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(context,Client_Second.class);
            startActivity(intent);
        }
    });

     //    Thread fst = new Thread(new ServerThread());
     //  fst.start();
    }


   public void receiveMessage()
    {
     new Thread(new Runnable() {

     public void run() {
         try {
             if (SERVERIP != null) {
                 handler.post(new Runnable() {
                     @Override
                     public void run() {
                         serverStatus.setText("Listening on IP: " + SERVERIP);
                     }
                 });
                 serverSocket = new ServerSocket(SERVERPORT);
                 while (true) {
                     // LISTEN FOR INCOMING CLIENTS
                     Socket client = serverSocket.accept();
                     handler.post(new Runnable() {
                         @Override
                         public void run() {
                             serverStatus.setText("Connected.");
                         }
                    });

                     try {
                        BufferedReader in = new BufferedReader(new             InputStreamReader(client.getInputStream()));
                        while(true) {
                        String line = null;
                        if ((line = in.readLine()) != null) {
                            Log.d("ServerActivity", line);
                             System.out.println(line);


                                    // DO WHATEVER YOU WANT TO THE FRONT END
                                    // THIS IS WHERE YOU CAN BE CREATIVE


                        }
                        else    {
                        break;
                        }
                        }

                    } catch (Exception e) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                serverStatus.setText("Oops. Connection interrupted.            Please reconnect your phones.");
                            }
                        });
                        e.printStackTrace();
                    }
                }
            } else {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        serverStatus.setText("Couldn't detect internet connection.");
                    }
                });
            }
        } catch (Exception e) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    serverStatus.setText("Error");
                }
            });
            e.printStackTrace();
        }
        }


  }).start();
  }

  // GETS THE IP ADDRESS OF YOUR PHONE'S NETWORK
 private String getLocalIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();    en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); }
            }
        }
    } catch (SocketException ex) {
        Log.e("Server_Second", ex.toString());
    }
    return null;
}

@Override
protected void onStop() {
    super.onStop();
    try {
         // MAKE SURE YOU CLOSE THE SOCKET UPON EXITING
         serverSocket.close();
     } catch (IOException e) {
         e.printStackTrace();
     }

}

}

1 个答案:

答案 0 :(得分:0)

每次用户按下某个键时,代码将重新输入sendMessage(),这将创建一个新的套接字连接,然后永远循环发送密钥(因为“connected”变量永远不会设置为false而str1永远不会更改)。

您需要重新设计它以在线程之间传递数据,以便仅在套接字上发送新数据。

您不应该在XML中使用clickHandler,将其连接到代码中。在XML中使用它可能会遇到问题(例如,使用proguard)。只需使用findViewById(R.id.f).setOnClickListener(...)