转-openfire+smack简单实时通信
http://blog.csdn.net/sapphire_aling/article/details/6674480
最近刚刚接触openfire,用它实现了简单的实时通信,这里只实现了两个特定的用户之间消息的发送,分享给像我一样的初学者
1、下载安装openfire
下载地址http://www.igniterealtime.org/projects/openfire/index.jsp
下载smack api包:http://www.igniterealtime.org/projects/smack/index.jsp
2、安装完openfire后,点击launch admin 进行设置,设置完成后登录,用户名为admin,密码就是你刚刚设置的密码。
3、新建两个用户用于一会通信的实现用户
4、具体实现:
新建一个java project,把smack api里面的四个jar包引进来
package com.koubei;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.Chat;
import java.io.*;
public class UserChat {
public static void chatuser(final Connection conn){
ChatManager manager = conn.getChatManager();
final MessageListener messagelistener = new MessageListener(){
@Override
public void processMessage(Chat chat,
Message message) {
System.out.println(conn.getUser()+" Received message:"+message.getBody());
}
};
manager.addChatListener(
new ChatManagerListener() {
@Override
public void chatCreated(Chat chat,
boolean createdLocally) {
if (!createdLocally)
chat.addMessageListener(messagelistener);
}
});
}
//主函数,与服务器连接、用户登录、发送消息都是从这里实现的
public static void main(String[] args){
ConnectionConfiguration config = new ConnectionConfiguration("127.0.0.1",5222); //第一个参数是你的openfire服务器地址,5222是openfire通信的端口
config.setCompressionEnabled(true);
config.setSASLAuthenticationEnabled(true);
Connection connection = new XMPPConnection(config);
Connection conn = new XMPPConnection(config);
try {
connection.connect();
conn.connect();
connection.login("墨阳", "111111");
conn.login("以陌", "111111");
ChatManager chatManager = connection.getChatManager();
Chat chat = chatManager.createChat("以陌@aliyun-40368/Smack", new MessageListener(){ //这里第一个参数是接收人的地址,不能只写用户名,具体是什么可以在上面先用System.out.println(conn.getUser());把用户的具体表示方法打印出来看看
@Override
public void processMessage(Chat chat,
Message message) {
System.out.println("Received message:"+message);
}
});
while(true){
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String message="";
System.out.println(connection.getUser()+" Please input the message:");
try{
message=br.readLine();
}catch(IOException e){
e.printStackTrace();
}
chatuser(conn);
chat.sendMessage(message);
}
} catch (XMPPException e) {
e.printStackTrace();
System.out.println("Error Delivering block");
}
connection.disconnect();
}
}
while循环实现了反复发送消息的功能
以上就是两个固定的用户之间发送消息,需要注意的就是接收消息人的写法。