这问题纠结了很久 用JAVA的 ObjectOutputStream 方法行不通
后来参考文章 发现最简单的办法还是JAVA端发送BYTE字节流 http://www.eifr.com/article.php?id=1396
http://hi.baidu.com/tweetyf/item/c2877cb44e733775254b099c
规定好 多少到多少字节应该写什么内容 在C++端按同样原则进行解码 话不多说 下面看代码
public class CMessage {
int flag = 0;
String username = null;
String password = null;
public byte[] buf = new byte[50];
public CMessage(int flag, String username, String password) {
this.flag = flag;
this.username = username;
this.password = password;
byte[] temp = null;
int num = 0;
num = username.getBytes().length;
temp = common.toLH(flag);
System.arraycopy(temp, 0, buf, 0, temp.length);
temp = username.getBytes();
System.arraycopy(temp, 0, buf, 4, temp.length);
temp = password.getBytes();
System.arraycopy(temp, 0, buf, 4 + num, temp.length);
}
public byte[] getBuf() {
return buf;
}
public CMessage() {
}
public class common {
/*将INT型转换为 低字节在前 高字节在后的BYTE数组*/
public static byte[] toLH(int n) {
byte[] b = new byte[4];
b[0] = (byte) (n & 0xff);
b[1] = (byte) (n >> 8 & 0xff);
b[2] = (byte) (n >> 16 & 0xff);
b[3] = (byte) (n >> 24 & 0xff);
return b;
}
/*反向转换BYTE数组与 INT 型数据*/
public static int bytes2Integer(byte[] byteVal) {
int result = 0;
for (int i = 0; i < byteVal.length; i++) {
int tmpVal = (byteVal[i] << (8 * (3 - i)));
switch (i) {
case 0:
tmpVal = tmpVal & 0xFF000000;
break;
case 1:
tmpVal = tmpVal & 0x00FF0000;
break;
case 2:
tmpVal = tmpVal & 0x0000FF00;
break;
case 3:
tmpVal = tmpVal & 0x000000FF;
break;
}
result = result | tmpVal;
}
return result;
}
}
按钮点击响应函数
mButton1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
Socket socket = new Socket("10.6.12.190", 6002);
/* 先获取输入的用户名和密码 trim 去除转义字符 */
String username = null;
String password = null;
int flag = 0;
EditText b1 = (EditText) findViewById(R.id.widget69);
EditText b2 = (EditText) findViewById(R.id.widget70);
username = b1.getText().toString();
password = b2.getText().toString();
/* 以下部分进行串行化 发送至服务器 */
// CMessage msg=new
// CMessage(flag,username,password);
CMessage cs =new CMessage(flag, username, password);
socket.getOutputStream().write(cs.getBuf());
socket.getOutputStream().flush();
//socket.getOutputStream().close();
byte[] recv=null;
socket.getInputStream().read(recv,0,4);
if (recv.length!=0) {
if (common.bytes2Integer(recv) == 0) {
Toast.makeText(MainActivity.this,
"登陆成功", 1000).show();
Intent intent = new Intent(
MainActivity.this,
LoadActivity.class);
startActivity(intent);
}
else {
/* 弹窗用户名或者密码错误 */
Toast.makeText(MainActivity.this,
"用户名或密码错误", 1000).show();
}
}
else {
Toast.makeText(MainActivity.this, "网络异常!",
1000).show();
}
}
catch (Exception e) {
Toast.makeText(MainActivity.this, "网络异常!", 1000)
.show();
e.printStackTrace();
}
}
});