在(1)中,实现了Windows服务端与Android客户端的连接,本节将实现在Windows服务端与Android客户端之间传递数据。
Android客户端的发送线程SendThread.java代码:
package com.hzhi.mouse_mb;
import java.io.DataOutputStream;
import java.net.Socket;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
public class SendThread extends Thread {
public static Socket socket_client;
public static String str_mk;
// DOS
DataOutputStream dos = null;
// 消息变量
private Message msg;
private Bundle bdl;
public SendThread(Socket skt){
socket_client = skt;
}
public void set_str(String str){
str_mk = str;
}
public void run(){
try
{
dos = new DataOutputStream(socket_client.getOutputStream());
}
catch (Exception e)
{
send_message(MainActivity.msg_error,e.toString());
}
while(true){
try
{
if(str_mk == null)
{
continue;
}
else
{
dos.writeUTF(str_mk);
Log.i("str_mk=", str_mk);
str_mk = null;
}
}
catch (Exception e)
{
send_message(MainActivity.msg_error,e.toString());
}
}
}
// 发送消息(用于更新UI)
public void send_message(int x, String s){
msg = new Message();
bdl = new Bundle();
bdl.putString("1",s);
msg.what = x;
msg.setData(bdl);
MainActivity.main_handler.sendMessage(msg);
}
}
dos = new DataOutputStream(socket_client.getOutputStream())获得了一个DataOutputStream,socket_client.getOutputStream()获得了将数据写入socket_client的OutputStream,并将该OutputStream作为dos的OutputStream;在while(true)循环中,dos.writeUTF(str_mk),将字符串str_mk写入socket_client,发送给服务端的Socket。
Windows服务端的接收线程tReceive.java代码:
import java.io.DataInputStream;
import java.net.Socket;
public class tReceive extends Thread{
public static Socket sct;
String str_mk;
public tReceive(Socket s) {
super("");
this.sct = s;
}
public void run() {
DataInputStream dis = null;
try
{
dis = new DataInputStream(sct.getInputStream());
}
catch (Exception e)
{
fMain.l_status.setText("错误:" + e);
}
while(true)
{
try
{
str_mk = dis.readUTF();
System.out.println("str_mk=" + str_mk);
fMain.rbt_act(str_mk);
}
catch (Exception e)
{
fMain.l_status.setText("错误:" + e);
}
}
}
}
dis = new DataInputStream(sct.getInputStream()) 获得了一个DataInputStream;sct.getInputStream()) 获得了sct的InputStream,并将该InputStream作为DataInputStream的InputStream;在while(true)循环中,dis.readUTF()读出sct中的数据,并赋值给字符串变量str_mk。