基于XMPP利用openfire简单的即时通讯

时间:2021-03-04 09:57:39

功能的实现结果:能够使自己编写客户端与spark客户端信息通讯,将接受到的信息更新到textview上。

1.下载openfire并安装。设置域名,添加用户

2.下载安装spark客户端

3.jar包 :asmack.jar

4.权限:

 <uses-permission android:name="android.permission.INTERNET"/>

5.简单布局:

     <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="login"
android:text="登录"
android:id="@+id/button" /> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="sendMsg"
android:text="发送消息"
android:id="@+id/button2"
android:layout_gravity="center_vertical" /> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="@+id/content" />

6.Activity代码:

 public class MainActivity extends AppCompatActivity {

     XMPPConnection con;
TextView tv;
//用于刷新textview的信息text
Handler hand=new Handler(){
@Override
public void handleMessage(android.os.Message msg) {
tv.setText(msg.obj.toString());
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
initView();
} private void initView() {
tv= (TextView) findViewById(R.id.content);
} private void init() {
new Thread(){
@Override
public void run() {
try {
//指定连接的ip地址和端口 以及服务器的域名
ConnectionConfiguration config=new ConnectionConfiguration("10.8.167.75",5222,"gxw");
//连接对象
con =new XMPPConnection(config);
//开启连接
con.connect();
} catch (Exception e) {
e.printStackTrace();
}
}
}.start(); }
public void login(View v){
try {
//登陆的用户账号和密码
con.login("bb","123456x");
System.out.print("");
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendMsg(View v){ ChatManager cm = con.getChatManager();
cm.addChatListener(new ChatManagerListener() {
@Override
public void chatCreated(Chat chat, boolean b) {
chat.addMessageListener(new MessageListener() {
@Override
public void processMessage(Chat chat, Message message) {
android.os.Message msg= android.os.Message.obtain();
if (!TextUtils.isEmpty(message.getBody())){
msg.obj=message.getBody();
hand.sendMessage(msg);
}
}
});
}
}); //aa为进行通信的账号,@后为域名
Chat chat = cm.createChat("aa@gxw",null);
try {
chat.sendMessage("1111111");
} catch (Exception e) {
e.printStackTrace();
}
}
}