Android设备向Server发送文本

时间:2014-03-18 06:33:20

标签: android multithreading

我正在尝试使用以下代码从Android设备向服务器发送字符串:

package com.example.androidsocketserver;

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

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {


    private Socket socket;

    private static final int SERVERPORT = 6000;
    private static final String SERVER_IP = "10.50.27.10";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);     

        new Thread(new ClientThread()).start();
    }

    public void onClick(View view) {
        try {
            EditText et = (EditText) findViewById(R.id.EditText01);
            String str = et.getText().toString();
            PrintWriter out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())),
                    true);
            out.println(str);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class ClientThread implements Runnable {

        @Override
        public void run() {

            try {
                InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

                socket = new Socket(serverAddr, SERVERPORT);

            } catch (UnknownHostException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

        }

    }
}

但它只是在第一次点击时发送字符串。在第二次它无法发送内容。我需要做什么?

1 个答案:

答案 0 :(得分:0)

  

但它只是在第一次点击时发送字符串。第二次是   无法发送内容。我需要做什么?

new Thread(new ClientThread()).start();放在一个单独的方法中说:

startThread(){
new Thread(new ClientThread()).start();
}

然后在onClick

中调用此方法