Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/223.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Android客户端套接字,如何读取数据?_Java_Android_Eclipse_Sockets_Client Side - Fatal编程技术网

Java Android客户端套接字,如何读取数据?

Java Android客户端套接字,如何读取数据?,java,android,eclipse,sockets,client-side,Java,Android,Eclipse,Sockets,Client Side,这是我的完整代码:cnx已建立,我正在向服务器发送数据,但我无法从服务器读取任何内容 public class client extends Activity { /** Called when the activity is first created. */ Socket sock; String spliter = "**"; String mobileNbr = "100"; String LastJOKEId = "-1"; String

这是我的完整代码:cnx已建立,我正在向服务器发送数据,但我无法从服务器读取任何内容

public class client extends Activity
{
    /** Called when the activity is first created. */
    Socket sock;
    String spliter = "**";
    String mobileNbr = "100";
    String LastJOKEId = "-1";
    String spliterlast = "^^$$";
    BufferedReader inFromServer;
    DataOutputStream outToServer;
    TextView cnx;
    TextView output;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setupNetworking();
        // Thread readerThread=new Thread(new IncomingReader());
        // readerThread.start();
    }

    private void setupNetworking()
    {
        try
        {
            Log.i("ClientActivity", "Connecting...");
            sock = new Socket("192.168.153.221", 9003);
            cnx = (TextView) findViewById(R.id.textView1);
            cnx.setText("Network Established.");
            inFromServer = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            Log.i("ClientActivity", "Sending command.");
            outToServer = new DataOutputStream(sock.getOutputStream());
            String sentence = "logins" + spliter + mobileNbr + spliter + LastJOKEId + spliterlast;
            outToServer.writeBytes(sentence + '\n');
            Log.i("ClientActivity", "Sent.");
        }
        catch (UnknownHostException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            cnx = (TextView) findViewById(R.id.textView1);
            cnx.setText("Network failed");
            e.printStackTrace();
        }
    }

    public class IncomingReader implements Runnable
    {
        String message;
        public void run()
        {
            try
            {
                while ((message = inFromServer.readLine()) != null)
                {
                    output = (TextView) findViewById(R.id.textView2);
                    output.setText(message);
                }
            }
            catch (IOException e)
            {
                output = (TextView) findViewById(R.id.textView2);
                output.setText("nth to display");
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
//---------------------------使用NetClient------------------------------------------------

NetClient nc = new NetClient(host, port, mac); //mac address maybe not for you
nc.sendDataWithString("your data");
String r = nc.receiveDataFromServer();

这是我们的android socket客户端,可以与Python服务器socket配合使用,希望它能帮助您。

我什么都没有得到:S什么都没有发生……您调试过这个部分吗?如何声明/处理您的
InforomServer
?您应该尝试捕获
Exception
而不是
IOException
,因为可能也很容易出现
NullPointerException
。另外,如果最后一行是空/空白字符串,则
TextViwe
不会显示任何内容。您应该尝试使用而不是
setText
谢谢您,rekaszeru…您给了我一个解决问题的提示。它成功了,现在我可以读取我的数据:D
 package some;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class NetClient {

    /**
     * Maximum size of buffer
     */
    public static final int BUFFER_SIZE = 2048;
    private Socket socket = null;
    private PrintWriter out = null;
    private BufferedReader in = null;

    private String host = null;
    private String macAddress = null;
    private int port = 7999;


    /**
     * Constructor with Host, Port and MAC Address
     * @param host
     * @param port
     * @param macAddress
     */
    public NetClient(String host, int port, String macAddress) {
        this.host = host;
        this.port = port;
        this.macAddress = macAddress;
    }

    private void connectWithServer() {
        try {
            if (socket == null) {
                socket = new Socket(this.host, this.port);
                out = new PrintWriter(socket.getOutputStream());
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void disConnectWithServer() {
        if (socket != null) {
            if (socket.isConnected()) {
                try {
                    in.close();
                    out.close();
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void sendDataWithString(String message) {
        if (message != null) {
            connectWithServer();
            out.write(message);
            out.flush();
        }
    }

    public String receiveDataFromServer() {
        try {
            String message = "";
            int charsRead = 0;
            char[] buffer = new char[BUFFER_SIZE];

            while ((charsRead = in.read(buffer)) != -1) {
                message += new String(buffer).substring(0, charsRead);
            }

            disConnectWithServer(); // disconnect server
            return message;
        } catch (IOException e) {
            return "Error receiving response:  " + e.getMessage();
        }
    }


}
NetClient nc = new NetClient(host, port, mac); //mac address maybe not for you
nc.sendDataWithString("your data");
String r = nc.receiveDataFromServer();