androidsocket通信创建线程接受客户端
//声明量
为正镶白等地区用户提供了全套网页设计制作服务,及正镶白网站建设行业解决方案。主营业务为成都网站设计、成都做网站、正镶白网站设计,以传统方式定制建设网站,并提供域名空间备案等一条龙服务,秉承以专业、用心的态度为用户提供真诚的服务。我们深信只要达到每一位用户的要求,就会得到认可,从而选择与我们长期合作。这样,我们也可以走得更远!
private String IPaddress="192.168.1.120";
private int port =50003;
private Handler mhandler =null;
private String cc ="";
private TextView returnvalue;
// 动态接收数据
mhandler = new Handler(){
public voidhandleMessage(Message msg)
{
if(msg.what== 1)
{
if(cc!=null||cc!="")
{
returnvalue.setText(cc);
cc=null;
}
}
super.handleMessage(msg);
}
};
//启动相关线程
serverThread thread = new serverThread();
thread.start();
//创建并发送数据
byte[] buf = {(byte)0x55,(byte)0xAA};
try {
socket = newSocket(this.IPaddress,this.port);
OutputStream out =socket.getOutputStream();
OutputStreamWriter writer =new OutputStreamWriter(out);
out.write(buf);
writer.flush();
Toast.makeText(PauseActivity.this,"成功",
Toast.LENGTH_SHORT).show();
} catch (UnknownHostExceptione) {
Toast.makeText(PauseActivity.this, "异常",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//接受数据
public class serverThread extendsThread {
publicvoid run() {
while(!Thread.currentThread().isInterrupted()){
if(socket==null)
{
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
// TODOAuto-generated catch block
e.printStackTrace();
}
}else
{
try {
Thread.sleep(1000);
InputStreamips=socket.getInputStream();
InputStreamReader in = new InputStreamReader(ips);
in.ready();
cc ="";
for(inti= 0 ;i<2 ;i++)
{
cc+=ips.read()+"-";
}
} catch(InterruptedException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
Message msg = newMessage();
msg.what= 1;
mhandler.sendMessage(msg);
}
}
}
}
//新人求关注
网站标题:androidsocket通信创建线程接受客户端
转载来于:http://myzitong.com/article/jsdjos.html