编写了android socket通信的软件,可以和主机通讯互相收发数据。但是一个字节的数据超过0x80就会乱码,也就是说如果数据小于128,那么正常超过就会乱码。请问这是哪里有问题。我确认硬件没有问题,换了设备也是可以的。
public class Tcp40Activity extends Activity {
/** Called when the activity is first created. */
Button BnSend;
EditText EtSend;
TextView TvRev ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
BnSend = (Button) findViewById(R.id.BnSend);//得到布局中的按钮引用
EtSend = (EditText) findViewById(R.id.MsgText);
TvRev = (TextView) findViewById(R.id.RevText);
BnSend.setOnClickListener(BnSendListen);
}
private View.OnClickListener BnSendListen=new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
char[] a ={0xF1,0x03,0x10,0x00,0x00,0x08,0x54,0x3C};
String str =String.valueOf(a);//String.copylueOf(a);
Socket s=null;
DataOutputStream dout=null;
DataInputStream din =null;
try
{
s =new Socket("192.168.1.1",8080);
dout =new DataOutputStream(s.getOutputStream());
din =new DataInputStream (s.getInputStream());
Thread.sleep(50, 0); //实际中刚连上后发数据需要一定延时 确保双方链接初始化完成
dout.writeBytes(str);
dout.flush(); //刷新缓存 发送数据
/*50秒内等待反馈*/
for(int i=0;i<100;i++)
{
if(din.available()>0)
{
byte[] buffer=new byte[din.available()];
System.out.println(din.available());
din.read(buffer);
TvRev.setText("服务器发来的消息:"+str2HexStr(new String(buffer)));
break;
}
else Thread.sleep(500, 0);
};
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try{
if(dout != null){
dout.close();
}
if(din != null){
din.close();
}
if(s != null){
s.close();
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
};
//16进制转换的显示测试
public static String str2HexStr(String str)
{
char[] chars = "0123456789ABCDEF".toCharArray();
StringBuilder sb = new StringBuilder("");
byte[] bs = str.getBytes();
int bit;
for (int i = 0; i < bs.length; i++)
{
bit = (bs[i] & 0x0f0) >> 4;
sb.append(chars[bit]);
bit = bs[i] & 0x0f;
sb.append(chars[bit]);
sb.append(' ');
}
return sb.toString().trim();
}
}