黑马程序员技术交流社区
标题:
Android群聊
[打印本页]
作者:
老衲玩IT
时间:
2013-8-25 15:32
标题:
Android群聊
/**
* 面向非连接的聊天程序
* @author 老衲玩IT
*
*/
public class ChatSocket{
private static final String HOST ="localhost";//"www.huajunadroid.iego.cn"; //"www.huajunadroid.iego.cn";
private static final int PORT = 8001;
DanceActivity activity;//
public ChatSocket() {
}
public ChatSocket(DanceActivity activity) {
this.activity=activity;
receive();
}
public void send(String msg) {
try {
DatagramSocket socket=new DatagramSocket();
//数据包
DatagramPacket packet=new DatagramPacket(msg.getBytes("UTF-8"), msg.getBytes().length,
InetAddress.getByName(HOST), PORT);
//发送
socket.send(packet);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void receive() {
new Thread(){
@Override
public void run() {
DatagramSocket socket=null;
try {
socket = new DatagramSocket(PORT);
byte[] data=new byte[1024];
while (true) {
DatagramPacket packet=new DatagramPacket(data, data.length);
//接收数据包
socket.receive(packet);
//strChatMsg是StringBuilder对象,添加聊天信息
activity.strChatMsg.append(new String(data,0,data.length)+"\n");
//为了线程安全,通过activity中的Handler对象通知activity中的TextView控件更新内容
activity.handler.sendEmptyMessage(DanceActivity.UPDATE_CHAT);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
if(socket!=null){
socket.close();
}
}finally{
//socket.disconnect();
if(socket!=null){
socket.close();
}
}
}
}.start();
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2