java c++ socket
各位好,我想做一个安卓传感器监听器,通过wifi链接,服务器端用java做的server已经通过,但是要用到openGL,必须要用c++做server。想请教c++怎样接收java发过来的String,下面是部分android代码。
void sendMessage(String message){
if (isStarted) {
try {
out.write(message.getBytes());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(message);
}
@Override
public void onSensorChanged(SensorEvent e) {
// TODO Auto-generated method stub
switch(e.sensor.getType()){
case Sensor.TYPE_ACCELEROMETER:{
String message =
"ACC" +
" " +
new Float(e.values[SensorManager.DATA_X]).toString() +
" " +
new Float(e.values[SensorManager.DATA_Y]).toString() +
" " +
new Float(e.values[SensorManager.DATA_Z]).toString() +
" ";
sendMessage(message);
break;
}
case Sensor.TYPE_ORIENTATION:{
String message =
"ORI" +
" " +
new Float(e.values[SensorManager.DATA_X]).toString() +
" " +
new Float(e.values[SensorManager.DATA_Y]).toString() +
" " +
new Float(e.values[SensorManager.DATA_Z]).toString() +
" ";
sendMessage(message);
break;
}
}
}
Answers
android端发送的报文最终要根据C++端的解析方式而定,传输过程中要注意报文长度约束和编码方式,例如:String xml = "<xml version=\"1.0\" encoding=\"GB18030\"?>";
xml = xml + "<root>";
xml=xml+ "<tranCode>ICDATE</tranCode>" +
"<channel_from>IC</channel_from>" +
"<tellerDate></tellerDate>" +
"<tellerTime></tellerTime>" +
"<branchCode></branchCode>" +
"<terminalNo></terminalNo>" +
"<tellerNo></tellerNo>" +
"<authorizeTeller></authorizeTeller>" +
"<tellerSerial></tellerSerial>";
xml = xml + "</root>";
//IP
String ip = getSystemNode("*****");
//端口
int port=Integer.parseInt(getSystemNode("****"));
s = new Socket(InetAddress.getByName(ip), port);
// 套接字的IP地址和端口号
os = s.getOutputStream();
is = s.getInputStream();
byte[] Name = xml.getBytes("ISO-8859-1"); //编码统一
os.write(Name);// 向服务器发送消息
int len = is.read(serverSay);// 接受服务器消息