通过smack client + openfire server 实现 peer to peer communication

【0】README
1)本文旨在 给出源代码 实现 smack client + openfire server 实现 peer to peer communication
2)当然,代码中用到的 user 和 pass, 你需要事先在 openfire 里面注册;
3)also , you can checkout the source code  from  https://github.com/pacosonTang/core-java-volume/tree/master/coreJavaSupplement/smack_client

通过smack client + openfire server 实现 peer to peer communication_第1张图片

【2】代码如下 
// 客户端基础类
public class ClientBase {
	private XMPPTCPConnectionConfiguration conf;
	private AbstractXMPPConnection connection;
	private ChatManager chatManager;
	private Chat chat;

	/**
	 * @param args refers to an array with ordered values as follows: user, password, host, port.
	 */
	public ClientBase(String... args) {
		String username = args[0];
		String password = args[1];
		String host = args[2];
		String port = args[3];

		conf = XMPPTCPConnectionConfiguration.builder().setUsernameAndPassword(username, password).setServiceName(host)
				.setHost(host).setPort(Integer.valueOf(port))
				.setSecurityMode(SecurityMode.disabled) // (attention of this line about SSL authentication.)
				.build();
		connection = new XMPPTCPConnection(conf);
		chatManager = ChatManager.getInstanceFor(connection);
	}
	
	/**
	 * connect to and login in openfire server.
	 */
	public void connectAndLogin() {
		System.out.println("executing connectAndLogin method.");
		try {
			connection.connect();
			System.out.println("successfully connection.");
			connection.login(); // client logins into openfire server.
			System.out.println("successfully login.");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * create chat instance using ChatManager.(startup a thread)
	 */
	public Chat createChat(String toUser) {
		System.out.println("executing createChat method.");
		// create Chat chat instance with other clients.
		chat = chatManager.createChat(toUser, new ChatMessageListener() {
			@Override
			public void processMessage(Chat chat, Message message) {
				System.out.println("receiving " + message);
			}
		});
		
		// create the chat with specified user.(startup a thread)
//		Chat chat = client.createChat("[email protected]");
		MessageHandler handler = new MessageHandler(chat); 
		MessageHandler.Sender sender = handler.new Sender(); // creating inner class.
		new Thread(sender).start();
		return chat;
	}
	
	/**
	 * add ChatManagerListener to ChatManager.
	 * @param listener added into ChatManager instance.
	 */
	public void addChatListener(ChatManagerListener listener) {
		System.out.println("executing addChatListener method.");
		chatManager.addChatListener(listener);
	}
	
	/**
	 * get chat timestamp, also time recoded when the msg starts to send.
	 * @param msg 
	 * @return timestamp.
	 */
	public String getChatTimestamp(Message msg) {
		ExtensionElement delay = DelayInformation.from(msg);
		
		if(delay == null) {
			return null;
		}
		Date date = ((DelayInformation) delay).getStamp();
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
		return format.format(date);
	}

	public XMPPTCPConnectionConfiguration getConf() {
		return conf;
	}

	public AbstractXMPPConnection getConnection() {
		return connection;
	}

	public ChatManager getChatManager() {
		return chatManager;
	}

	public Chat getChat() {
		return chat;
	}
}
public class ClientA {
	public static void main(String a[]) throws Exception {
		Locale.setDefault(Locale.CHINA);
		ClientBase client = new ClientBase(
				new String[]{"tangtang", "tangtang", "csdn.pacosonswjtu.com", "5222"});
		
		client.connectAndLogin();
		client.addChatListener(new MyChatListener(client));
		
		// create the chat with specified user.(startup a thread)
		client.createChat("[email protected]");
	}
}
public class ClientB {
	public static void main(String a[]) throws Exception {
		Locale.setDefault(Locale.CHINA);
		ClientBase client = new ClientBase(
				new String[]{"pacoson", "pacoson", "csdn.pacosonswjtu.com", "5222"});
		
		client.connectAndLogin();
		client.addChatListener(new MyChatListener(client));
		
		// create the chat with specified user.(startup a thread)
		client.createChat("[email protected]");
	}
}

// 监听器
public class MyChatListener implements ChatManagerListener{
	private ClientBase client;
	
	public MyChatListener(ClientBase client) {
		this.client = client;
	}
	
	@Override
	public void chatCreated(Chat chat, boolean createdLocally) {
		if (!createdLocally) {
			chat.addMessageListener(new ChatMessageListener() {
				@Override
				public void processMessage(Chat chat, Message message) {
					String from = message.getFrom();
					Set<Body> bodies = message.getBodies();
					String timestamp = client.getChatTimestamp(message);
					
					if(timestamp != null) {
						System.out.println(timestamp);
					}
					for(Body b : bodies) {
						System.out.println(from + ":" + b.getMessage());
					}
				}
			});
		}
	}
}
// 创建发送msg 线程.
public class MessageHandler {
	private Chat chat;
	
	public MessageHandler(Chat chat) {
		this.chat = chat;
	}

	class Sender implements Runnable{
		/*public Sender(Chat chat) {
			MessageHandler.this.chat = chat;
		}*/
		public Sender() {}
		
		@Override
		public void run() {
			Scanner scanner = new Scanner(System.in);
			while(scanner.hasNext()) {
				String line = scanner.nextLine();
				try {
					chat.sendMessage(line);
				} catch (NotConnectedException e) {
					e.printStackTrace();
					break;
				}
			}
		} 
	}
	
	class Receiver {
		
	}
}
(干货——只有当 消息接收者处于离线的时候,其接收到的消息才会封装 delay 元素,其属性有 stamp 记录了 msg 发送的时间。(also, you can refer to https://community.igniterealtime.org/thread/22791)

你可能感兴趣的:(通过smack client + openfire server 实现 peer to peer communication)