日期:2014-05-20  浏览次数:21294 次

socket给服务端发送范围超过127的数据
private EditText ipStr;
private EditText portStr;
private EditText msgStr;
private TextView serverStr;
private String IP="192.168.1.100";
private String PORT="1000";
private char test[]={0x55,0xaa,0x01};
byte[] test2=new byte[20];
private Socket s = null;
private PrintWriter pw = null;
private BufferedReader br=null;
private Thread mThread=null;


  @Override
  public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  final Button btnSend = (Button) findViewById(R.id.btnSend);
  btnSend.setOnClickListener(onClickListener);
  ipStr = (EditText) findViewById(R.id.ipStr);
  ipStr.setText(IP);
  portStr = (EditText) findViewById(R.id.portStr);
  portStr.setText(PORT);
  msgStr = (EditText) findViewById(R.id.msgStr);
  serverStr = (TextView) findViewById(R.id.serverStr);
  String port = portStr.getText().toString().trim();

  try{
  s=new Socket(IP, Integer.parseInt(port));
  pw=new PrintWriter(new OutputStreamWriter(s.getOutputStream()), true); 
  //new OutputStreamWriter(socket.getOutputStream()));  

  br = new BufferedReader(new InputStreamReader(s.getInputStream()));
  }catch (Exception e) {
e.printStackTrace();
}
  mThread=new Thread(mRunnable);
  mThread.start();
  }
   
  private OnClickListener onClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new TCPAndroidClient()).run();
}
};

class TCPAndroidClient implements Runnable {
String msg = msgStr.getText().toString().trim();
@Override
public void run() {
if (s.isConnected()) {  
if (!s.isOutputShutdown()) { 
pw.println(test);
 
}
}
}

客户端接收到的数据是55 C2 AA 01 0A,那个aa前面有个C2,不知道为什么,只要test[]内有个大于0x7f的char,就会多了个C2,为什么

------解决方案--------------------
探讨

引用:
用OutputStream调用write(buf)发送byte[]吧,就没这个问题了。

Writer有字符编码转换的问题,而你发送的又是二进制格式。除你显示编码成ISO-8859-1编码类型。

请问怎样用 用OutputStream调用write(buf),是用对象(PrintWriter)pw.write(buf)吗?我试过用这个方法……