今天做一个android与pc通信的小demo(不是wifi,蓝牙)android为客户端,pc为服务器(一对多)。pc代码很简单,android客户端代码也不难,但是有一点不太明白就是在客户端向服务器发送消息时要用
writer= new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
用writer = new PrintWriter(socket.getOutputStream(), true)这句服务器接收不到消息!
(BufferedWriter主要提供了字符输出的缓冲功能,提高了字符输出的效率。
OutputStreamWriter则是一个字符输出流到字节输出流的桥梁,负责字符编码的转换。主要作用 是将字符编码转换为字节编码,以便能够输出到各种设备或文件中。
OutputStream,是更底层的字节输出流,不涉及字符编码的转换)
先记录一下,以备后用!
以下代码为自己实验备份可以用(测试过的)但很不严谨
public class MainActivity extends Activity implements OnClickListener {
public TextView textView;
public Socket socket;
public PrintWriter writer;
private Button btn;
private EditText editText;
public static final int UPDATE_TEXT=1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.text_view);
btn=(Button)findViewById(R.id.button);
editText=(EditText)findViewById(R.id.edit_text);
btn.setOnClickListener(this);
//new ConnectTask().execute();
new Thread(new Runnable() {
//PrintWriter out;
@Override
public void run() {
try {
socket = new Socket("192.168.1.3", 1982);
Log.d("MainActivity", "网络初始化成功");
writer= new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// writer.println("wochaolezhangyuhui");
} catch (UnknownHostException e) {
e.printStackTrace();
Log.d("MainActivity", "未知主机地址");
} catch (IOException e) {
e.printStackTrace();
Log.d("MainActivity", "输入输出异常");
}
}
}).start();
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.button:
String str=editText.getText().toString();
writer.println(str);
}
}
/*class ConnectTask extends AsyncTask<Void, Void, Void> {
private Socket socket;
PrintWriter out;
@Override
protected Void doInBackground(Void... params) {
try {
socket = new Socket("192.168.1.3", 1982); // 替换为PC的IP地址
//out= new PrintWriter(socket.getOutputStream());
out= new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.write("wochaolezhangyuhui");
btn.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//String str=editText.getText();
out.write("wochaolezhangyuhui");
}});
//in.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
*/
}