Java 安卓需要帮助!如何使Tcp客户端从服务器接收数据?

Java 安卓需要帮助!如何使Tcp客户端从服务器接收数据?,java,android,sockets,tcp,Java,Android,Sockets,Tcp,我想做一个TCP客户端,可以为服务器发送和接收数据。我使用Hercules(TCP/UDP测试程序)作为服务器。我的代码可以向服务器发送字符串“Submit”。我试着让我的代码可以接收来自Hercules的数据,但它不起作用。我要做什么来编辑它 这是我的主要活动代码 public class MainActivity extends Activity { // Used to reference UI elements of main.xml private TextView text,ser

我想做一个TCP客户端,可以为服务器发送和接收数据。我使用Hercules(TCP/UDP测试程序)作为服务器。我的代码可以向服务器发送字符串“Submit”。我试着让我的代码可以接收来自Hercules的数据,但它不起作用。我要做什么来编辑它

这是我的主要活动代码

public class MainActivity extends Activity {

// Used to reference UI elements of main.xml
private TextView text,serverResponse;
private EditText ipBox;
private EditText portBox;
private ToggleButton connect;
private Button send;
private static final String TAG = "CClient"; 
private String ipAddress;
private Socket client;
private DataOutputStream outToServer;
private DataInputStream inFromServer;
private boolean connected = false;   
private final int START = 0xffffff;
private final int msgBoxHint = START;
private final int appendText = START + 1;
Toast mytoast , savetoast;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    Log.d(TAG, "Here 1");
    ipAddress = getLocalIpAddress();
    Log.d(TAG, "Get local IP="+ ipAddress);
    text = (TextView) findViewById(R.id.text);
    ipBox =  (EditText) findViewById(R.id.ipBox);
    serverResponse = (TextView) findViewById(R.id.response);
    portBox =  (EditText) findViewById(R.id.portBox);
    send = (Button) findViewById(R.id.send);
    send.setOnClickListener(buttonsendOnClickListener);      
    connect = (ToggleButton) findViewById(R.id.connect);      
    connect.setOnClickListener(buttonConnectOnClickListener);
    Button buttonExit = (Button) findViewById(R.id.btnExit);
    buttonExit.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.d(TAG, "Exit");
            Log.d(TAG, "Disconnect" );
            if(client != null)
            {
                try {
                    client.close();
                } catch (IOException e) {
                 Log.d(TAG, "Disconnect"+e.toString() );
                }
            } 
            finish();
        }
    });  
}

OnClickListener buttonConnectOnClickListener = new OnClickListener() {    
/** Manages all button clicks from the screen */
@TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override
public void onClick(View arg0) {
    switch(arg0.getId())
    {
        case R.id.connect:
             if(connect.isChecked())
             {
                 Log.d(TAG, "Connect" );

                 EditText edIP = (EditText) findViewById(R.id.ipBox);
         String ed_textIP = edIP.getText().toString().trim();
         if(ed_textIP.isEmpty() || ed_textIP.length() == 0 || ed_textIP.equals("") || ed_textIP == null )
         {
             Toast.makeText(MainActivity.this, "IP Address or PORT is incorrect", Toast.LENGTH_SHORT).show();
             Log.d(TAG, "IP Address or PORT is incorrect");
         }
                    setValues(R.id.connect,true);
                    setValues(R.id.send,true);
                    setValues(R.id.ipBox,false);
                String tMsg = welcomeMsg.toString();
                MyClientTask myClientTask = new MyClientTask(ipBox
                        .getText().toString(), Integer.parseInt(portBox
                        .getText().toString()),
                        tMsg);


                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                    myClientTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                else
                    myClientTask.execute();
             }
             else
             { /*Toast.makeText(this, ipBox.getText(), Toast.LENGTH_LONG).show();*/
                 Log.d(TAG, "Disconnect" );
                 if(client != null)
                 {
                     try {
                         client.close();
                     } catch (IOException e) {
                         Log.d(TAG, "Disconnect"+e.toString() );
                     }

                     setText(R.id.text,"Press the connect button to start the client");
                     setText(msgBoxHint,"");

                     setValues(R.id.connect,false);
                     setValues(R.id.ipBox,true);
                     setValues(R.id.send,false);
                 }   
                 else
                 {
                     setValues(R.id.connect,false);
                 }
             }
             break;
    }
}
}; 

public class MyClientTask extends AsyncTask<Void, Void, Void> {

    String dstAddress;
    int dstPort;
    String response = "";
    String msgToServer;
    MyClientTask(String addr, int port, String msgTo) {
        dstAddress = addr;
        dstPort = port;
        msgToServer = msgTo;
    }

    protected Void doInBackground(Void... Arg0) {
        Log.d(TAG, "InBackground");
        Socket socket = null;
        DataOutputStream outToServer = null;
        DataInputStream inFromServer = null;

        try {
            client  = new Socket(dstAddress, dstPort);
            outToServer = new DataOutputStream(client.getOutputStream());       
            inFromServer =  new DataInputStream(new BufferedInputStream(client.getInputStream()));  // Input stream <- from server
        }catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            Log.d(TAG, "InBackground 1");
            e.printStackTrace();
            response = "UnknownHostException: " + e.toString();
            MainActivity.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    mytoast =  Toast.makeText(MainActivity.this, "Error UnknownHostException", 
                        Toast.LENGTH_SHORT);
                        mytoast.show();
                        setValues(R.id.send,false);
                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                           @Override
                           public void run() {
                               mytoast.cancel(); 
                           }
                    }, 500);                      
                }
            });
        } catch (IOException e) {
            Log.d(TAG, "InBackground 2");
            // TODO Auto-generated catch block
            e.printStackTrace();
            response = "IOException: " + e.toString();
            MainActivity.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    mytoast =  Toast.makeText(MainActivity.this, "Error IOException", 
                        Toast.LENGTH_SHORT);
                        mytoast.show();
                        setValues(R.id.connect,false);
                        setValues(R.id.send,false);
                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                           @Override
                           public void run() {
                               mytoast.cancel(); 
                           }
                    }, 500);

                }
            });
        }finally {
            Log.d(TAG, "InBackground 3");
            if (socket != null) {
                try {
                    socket.close();
                    Log.d(TAG, "InBackground 3.11");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Log.d(TAG, "InBackground 3.12");
                }
            }
            Log.d(TAG, "InBackground 3.1");
        }
        Log.d(TAG, "InBackground 4");
        return null;        
    }
    @Override
    protected void onPostExecute(Void result) {
        serverResponse.setText(response);
        super.onPostExecute(result);
    }
}

OnClickListener buttonsendOnClickListener = new OnClickListener() {    
    /** Manages all button clicks from the screen */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override
    public void onClick(View arg0) {
        switch(arg0.getId())
        {
            case R.id.send:
                     Log.d(TAG, "Sent" );
                     String sentence = "Submit";
                     String recieve = "";
                     serverResponse  = (TextView) findViewById(R.id.response);
                     try {
                        outToServer = new DataOutputStream(client.getOutputStream());       
                        inFromServer =  new DataInputStream(new BufferedInputStream(client.getInputStream()));
                         Log.d(TAG, "Sent 1-1" );     
                        if(sentence != null){
                            outToServer.writeUTF(sentence);
                            outToServer.flush();    
                        }

                        /*
                         * 
                         * 
                         * 
                         * 
                         * 
                         */
                        Log.d(TAG, "Sent 1-2"+ recieve);    



                     } catch (IOException e) {
                         setValues(R.id.ipBox,true);
                         setValues(R.id.connect,false);
                         setValues(R.id.send,false);
                     }
                     break;
        }
      }
    }; 

private String getLocalIpAddress() {
    Log.d(TAG, "Here 2");
    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    Log.d(TAG, "Here 3");
    WifiInfo info = wifi.getConnectionInfo();
    Log.d(TAG, "Here 4");
    return Formatter.formatIpAddress(info.getIpAddress());
}

private void setText(int view, String content)
{
    switch(view)
    {
        case R.id.ipBox: ipBox.setText(content); break;
        case R.id.text: text.setText(content+"\n\n"); break;
        case appendText: text.append(content+"\n\n"); break;
    }
}

private void setValues(int view, boolean value)
{
    switch(view)
    {
        case R.id.ipBox: ipBox.setEnabled(value); break;
        case R.id.send: send.setEnabled(value); break;
        case R.id.connect: connect.setChecked(value); break;
    }
}    
}
公共类MainActivity扩展活动{
//用于引用main.xml的UI元素
私有文本查看文本,服务器响应;
专用编辑文本框;
私有编辑文本端口盒;
专用切换按钮连接;
私人按钮发送;
私有静态最终字符串TAG=“CClient”;
私有字符串IP地址;
专用套接字客户端;
专用DataOutputStream outToServer;
专用数据输入流信息服务器;
私有布尔连接=假;
私有最终整数开始=0xffffff;
private final int msgBoxHint=开始;
私有final int appendText=START+1;
吐司我的吐司,保存吐司;
/**在首次创建活动时调用*/
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN\u ORIENTATION\u横向);
Log.d(标记“此处1”);
ipAddress=GetLocalicPaddress();
Log.d(标记“获取本地IP=“+ipAddress”);
text=(TextView)findViewById(R.id.text);
ipBox=(EditText)findViewById(R.id.ipBox);
serverResponse=(TextView)findViewById(R.id.response);
portBox=(EditText)findViewById(R.id.portBox);
send=(按钮)findviewbyd(R.id.send);
send.setOnClickListener(按钮SendOnClickListener);
connect=(切换按钮)findViewById(R.id.connect);
connect.setOnClickListener(按钮connectonclicklistener);
Button buttonExit=(Button)findViewById(R.id.btnExit);
buttonExit.setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图v){
日志d(标记“退出”);
日志d(标记“断开”);
如果(客户端!=null)
{
试一试{
client.close();
}捕获(IOE异常){
Log.d(标记“Disconnect”+e.toString());
}
} 
完成();
}
});  
}
OnClickListener按钮OnConnectionClickListener=新建OnClickListener(){
/**管理屏幕上的所有按钮单击*/
@TargetApi(Build.VERSION\u CODES.蜂巢)@覆盖
公共void onClick(视图arg0){
开关(arg0.getId())
{
案例R.id.connect:
if(connect.isChecked())
{
日志d(标记“连接”);
EditText edIP=(EditText)findViewById(R.id.ipBox);
字符串ed_textIP=edIP.getText().toString().trim();
如果(ed|textIP.isEmpty()| ed|textIP.length()==0 | ed|ed|textIP.equals(“”)| ed|ed|textIP==null)
{
Toast.makeText(MainActivity.this,“IP地址或端口不正确”,Toast.LENGTH_SHORT.show();
Log.d(标记“IP地址或端口不正确”);
}
设置值(R.id.connect,true);
设置值(R.id.send,true);
设置值(R.id.ipBox,false);
字符串tMsg=welcomeMsg.toString();
MyClientTask MyClientTask=新建MyClientTask(ipBox
.getText().toString(),Integer.parseInt(portBox
.getText().toString()),
tMsg);
if(Build.VERSION.SDK\u INT>=Build.VERSION\u code.HONEYCOMB)
myClientTask.executeOnExecutor(AsyncTask.THREAD\u POOL\u EXECUTOR);
其他的
myClientTask.execute();
}
其他的
{/*Toast.makeText(this,ipBox.getText(),Toast.LENGTH_LONG.show()*/
日志d(标记“断开”);
如果(客户端!=null)
{
试一试{
client.close();
}捕获(IOE异常){
Log.d(标记“Disconnect”+e.toString());
}
setText(R.id.text,“按连接按钮启动客户端”);
setText(msgBoxHint,“”);
设置值(R.id.connect,false);
设置值(R.id.ipBox,真);
设置值(R.id.send,false);
}   
其他的
{
设置值(R.id.connect,false);
}
}
打破
}
}
}; 
公共类MyClientTask扩展了AsyncTask{
字符串地址;
国际数据传输端口;
字符串响应=”;
字符串msgToServer;
MyClientTask(字符串地址、int端口、字符串msgTo){
dstAddress=addr;
dstPort=端口;
msgToServer=msgTo;
}
受保护的Void doInBackground(Void…Arg0){
日志d(标签“背景内”);
套接字=空;
DataOutputStream outToServer=null;
DataInputStream INFOROMSERVER=null;
试一试{
客户端=新套接字(DSTADRESS,dstPort);
outToServer=新的DataOutputStream(client.getOutputStream());

INFOROMSERVER=new DataInputStream(new BufferedInputStream(client.getInputStream());//输入流不能与主(gui)线程中的套接字一起工作。请使用AsyncTask!
如果在主(gui)线程中使用套接字,Android将失败

例如:

    new AsyncTask<Void, Void, Void>() {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // do in main thread before
            }

            @Override
            protected Void doInBackground(Void... v) {
                // do in thread, use sockets

                return null;
            }

            @Override
            protected void onPostExecute(Void v) {
                super.onPostExecute(integer);
                // do in main thread after
            }
        }.execute();  
newasynctask(){
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
//请在主线程中执行以下操作:
}
@凌驾
受保护的空位背景(空位…v){
//不要在螺纹中使用套筒
返回null;
}
@凌驾
受保护的void onPostExecute(void v){
onPostExecute(整数);
//用m表示