2013年8月15日星期四

android thread and handle communication problems?

The use of thread and handle can be achieved by using the TCP client wants to send data android, and then displayed on the textview on, but I send data on the part of the android, a little question, do not know how it is, no amount of reaction · ; experts look up, get a bit of a mess ah amount afternoon · · ·
I actually send data android major plus is that these two parts:

send_btn.setOnClickListener(new Button.OnClickListener(){
    @Override
    public void onClick(View v) {
    tmp = senddata_et.getText().toString();
    send_flag = true;
    }});


if(send_flag == true){
byteBuffer = tmp.getBytes();//byte[] bs = str.getBytes();//将string转byte
outputStream.write(byteBuffer, 0, tmp.length());
System.out.println(new String(byteBuffer,0,tmp.length()));
send_flag = false;
Message m2 = new Message();
//消息的标记GUINOTIFIER在前面定义的
                    m2.what = tcp_server.SENDOK;
                   //传送消息
                    tcp_server.this.mHandler.sendMessage(m2);
}

the other part of the code is not the problem, the following is all the code, I hope someone can have a look:

package com.FJICC.lzm;


import java.util.ArrayList;
import java.util.Enumeration;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.ServerSocket;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class tcp_server extends Activity{

private Button serverStart_btn;
private Button serverStop_btn;
private TextView receivedata_tv;
private Button setport_btn;
private EditText senddata_et;
private Button send_btn;
public int PORT = 8080;
public Handler mHandler;
protected static final int GUINOTIFIER = 0x1234;
protected static final int SENDOK = 0x1235;
public String tmp;
public boolean send_flag = false;

@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent i =new Intent();
i.setClass(tcp_server.this,MainActivity.class);
startActivity(i);
finish();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.tcpserver_main);

serverStart_btn=(Button)findViewById(R.id.btnStart);
serverStop_btn=(Button)findViewById(R.id.btnStop);
setport_btn=(Button)findViewById(R.id.btnSet);
send_btn=(Button)findViewById(R.id.btnSend);

senddata_et=(EditText)findViewById(R.id.et_send);
receivedata_tv=(TextView)findViewById(R.id.tv_receive);

serverStart_btn.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
serverStart_btn.setEnabled(false);
setport_btn.setEnabled(false);
serverStop_btn.setEnabled(true);

new Thread()
{
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
ServerSocket serverSocket=null;
try{
serverSocket = new ServerSocket(PORT);//创建ServerSocket对象监听PORT端口
Socket socket= serverSocket.accept();//接收tcp连接返回socket对象
InputStream inputStream=socket.getInputStream();//获得输入流
OutputStream outputStream = socket.getOutputStream();//获得输出流
byte []byteBuffer=new byte[1024];
int temp = 0;
String s;
//读取接收到的数据
while((temp = inputStream.read(byteBuffer))!=-1)
{
outputStream.write(byteBuffer, 0, temp);//原样返回 收到的数据

//将byte转为string//String(byte[], int, int)使用平台的缺省字符编码方式转换指定的字节子数组生成一新的 String
s = new String(byteBuffer,0,temp);

//byte[] bs = str.getBytes();//将string转byte

Message m = new Message();//定义一个message的变量m
                    m.what = tcp_server.GUINOTIFIER;//消息的标记GUINOTIFIER在前面定义的
                    m.obj =s; //将要传送的数据传递给 m.obj                    
                    tcp_server.this.mHandler.sendMessage(m);//传送消息
}
if(send_flag == true){
byteBuffer = tmp.getBytes();//byte[] bs = str.getBytes();//将string转byte
outputStream.write(byteBuffer, 0, tmp.length());
System.out.println(new String(byteBuffer,0,tmp.length()));
send_flag = false;
Message m2 = new Message();
//消息的标记GUINOTIFIER在前面定义的
                    m2.what = tcp_server.SENDOK;
                   //传送消息
                    tcp_server.this.mHandler.sendMessage(m2);
}
//System.out.println(new String(byteBuffer,0,temp));
outputStream.flush();
socket.close();
serverSocket.close();
                                       
}catch(IOException e){
e.printStackTrace();
}
}
}.start();
}
});

//创建handler
mHandler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {//得到Handle的通知了 这个时候你可以做相应的操作
                    case tcp_server.GUINOTIFIER://tcp_server是Activity的类名      
                    //清空textView
                    // receivedata_tv.setText("");
                    //设置textView显示内容
                    receivedata_tv.setText(msg.obj.toString());
                        break;
                    case tcp_server.SENDOK:
                    senddata_et.setText("");
                }
                super.handleMessage(msg);
            }
        };
        //结束TCP服务器
        serverStop_btn.setOnClickListener(new Button.OnClickListener(){
    @Override
    public void onClick(View v) {
    serverStart_btn.setEnabled(true);
    setport_btn.setEnabled(true);
    serverStop_btn.setEnabled(false);
   
    Intent i =new Intent();
    i.setClass(tcp_server.this,MainActivity.class);
    startActivity(i);
    finish();
    }});
        send_btn.setOnClickListener(new Button.OnClickListener(){
    @Override
    public void onClick(View v) {
    tmp = senddata_et.getText().toString();
    send_flag = true;
    }});
    }
}



In this first thank you ah ~ ~ ~
------ Solution --------------------------- -----------------

------ Solution ------------------------------- -------------
so long to do
---- - Solution --------------------------------------------
Roughly a look at the issue is still very large

byteBuffer = tmp.getBytes () ;/ / byte [] bs = str.getBytes () ;/ / will turn byte string
outputStream.write (byteBuffer, 0, tmp.length ());

You obviously spent byteBuffer but you actually call tmp.length ()

There

while ((temp = inputStream.read (byteBuffer))! = -1)
{
outputStream.write (byteBuffer, 0, temp) ;/ / returns the data received as

/ / The byte into string / / String (byte [], int, int) using the platform's default character encoding conversion specified byte array to generate a sub- new String
s = new String (byteBuffer, 0, temp);

/ / byte [] bs = str.getBytes () ;/ / will turn byte string ;

Message m = new Message () ;/ / define a message variable m
m.what = tcp_server.GUINOTIFIER ;/ / messages defined earlier mark GUINOTIFIER
m.obj = s; / / pass data to be transmitted to the m.obj ;
tcp_server.this.mHandler.sendMessage (m) ;/ / send the message
}

you have not the time to start sending you this thread has been estimated that the end of this thread should be used to receive a "dead loop" so as to have been received ah

------ For reference only ---------------------------------------
behind the source code, just to give reference, mainly in front of two short amount
------ For reference only ---------------------------- -----------
expert help, look ah · · Haha this time will not give the wrong divided ~ If answered correctly, I added points ah ~ ~
- ----- For reference only ---------------------------------------
actually want, get a TCP server, you can send and receive data. But many of them are looking for on the Internet is not the kind of interface, so I want to get yourself an amount of ~ ~ ~ Oh
now sent this one ~ ~ ~
------ For reference only -------------------------- -------------
my research inferior frontal · · · · ·

没有评论:

发表评论