抽象出来的两个模块:发送/接收
当然,我们要自己实现 对象 <--> byte[](字节数组) 的转换,因为j2ME没有那么强大的api,移动设备不允许。
序列化对象:
package po;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
public class LoginUser {
private String name;
private String password;
public LoginUser(String name, String pwd) {
this.name = name;
this.password = pwd;
}
public byte[] toBytes() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
try {
dos.writeUTF(this.getName());
dos.writeUTF(this.getPassword());
return baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
baos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
try {
dos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return null;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
信息接收线程
public class GeneralReceiver {
HttpConnection hc = null;
DataInputStream dis = null;
public GeneralReceiver(HttpConnection hc) {
this.hc = hc;
try {
this.dis = hc.openDataInputStream();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public byte[] getFeedback() {
boolean flag = true;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (flag) {
try {
int ch;
while ((ch = dis.read()) != -1) {
baos.write(ch);
}
return baos.toByteArray();
} catch (IOException ex) {
flag = false;
ex.printStackTrace();
}
}
try {
dis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
try {
hc.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
}
信息发生线程
package connection;
import java.io.DataOutputStream;
import java.io.IOException;
import javax.microedition.io.HttpConnection;
public class GeneralSender extends Thread {
DataOutputStream dos = null;
byte[] data = null;
public GeneralSender(HttpConnection hc, byte[] data) {
try {
this.dos = hc.openDataOutputStream();
} catch (IOException ex) {
ex.printStackTrace();
}
this.data = data;
}
public void run() {
try {
dos.write(this.data, 0, data.length);
dos.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (dos != null) {
try {
dos.close();
} catch (IOException e) {
}
}
}
}
}