Android编程实战——仿微信群聊-3——客户端实现
项目源代码移步github
客户端类有:Client,ClientMsgThread,MyMessage。
Client用来发送消息,ClientMsgThread是一个不断等待接收消息的线程。
Client类:
public class Client {
private Socket client;
private ObjectOutputStream oos = null;
private ObjectInputStream ois = null;
private LinkedBlockingDeque<MyMessage> msgQueue = null;
private ClientMsgThread clientMsgThread = null;
private final int PORT = 4243;
private final String SERVICE_ADDRESS = "192.168.191.1";
public Client() {
msgQueue = new LinkedBlockingDeque<>(100);
}
/**
* 连接服务器
*/
public void connect() {
if (client == null ) {
try {
System.out.println("请求连接服务器...");
client = new Socket(SERVICE_ADDRESS, PORT);
System.out.println("连接服务器成功");
oos = new ObjectOutputStream(client.getOutputStream());
ois = new ObjectInputStream(client.getInputStream());
clientMsgThread = new ClientMsgThread(ois);
clientMsgThread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 断开连接
*/
public void disconnect() {
if (client != null) {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 发送请求连接的消息
* @param name 登录姓名
* @return
*/
public boolean login(String name) {
connect();
boolean b =false;
try {
MyMessage myMessage = new MyMessage(MyMessage.MSG_LOGIN, name);
oos.writeObject(myMessage);
} catch (IOException e) {
e.printStackTrace();
}
return b;
}
/**
* 发送语音的消息
* @param filePath
* @param time
*/
public void sendAudioFile(String filePath, float time) {
connect();
int length = 0;
double sumL =