Asmack源码入门
Smack的初始化涉及到两个步骤: 1.初始化系统属性——通过SmackConfiguration进行系统属性初始化。这些属性可以通过getxxx()方法获
Smack的初始化涉及到两个步骤:
1.初始化系统属性——通过SmackConfiguration进行系统属性初始化。这些属性可以通过getxxx()方法获取。
2.初始化启动类——初始化类意味着在启动时候实例化该类,如果继承SmackInitializer则需要调用initialize()方法。如果不继承SmackInitializer则初始化的操作必须在静态代码块中,一旦加载类时自动执行。
Establishing a Connection创建连接
XmppTCPConnection类是被用来创建连接到xmpp服务器的。
// Create a connection to the jabber.org server._
XMPPConnection conn1 = new XMPPTCPConnection("jabber.org");
conn1.connect();
// Create a connection to the jabber.org server on a specific port._
ConnectionConfigurationconfig = new ConnectionConfiguration("jabber.org", 5222);
XMPPConnection conn2 = new XMPPTCPConnection(config);
conn2.connect();
ConectionConfiguration类提供一些控制操作,譬如是否加密。
Working with the Roster 花名册
Roster可以让你保持获取其他用户的presence状态,用户可以添加进组“Friend”或者“Co-workers”,你可以知晓用户是否在线。
检索roster可以通过XMPPConnection.getRoster()方法,roster类允许你查看所有的roster enteries ,群组信息当前的登录状态。
Reading and WritingPackets读写数据包
XMPP服务器和客户端间以XML传递的信息被称为数据包。
org.jivesoftware.smack.packet包内有三种封装好的基本的packet,分别是message, presence和IQ。
比如Chat和GroupChat类提供了更高级别的结构用以创建发送packet,当然你也可以直接用packet。
// Create a new presence. Pass in false to indicate we're unavailable._
Presence presence = new Presence(Presence.Type.unavailable);
presence.setStatus("Gone fishing");
// Send the packet (assume we have aXMPPConnection instance called "con").
con.sendPacket(presence);
Smack提供两种读取packets
PacketListener和PacketCollector,这两种都通过PacketFilter进行packet加工。
A packet listener is used for event style programming, while a packet collector has a result queue of packets that you can do polling and blocking operations on.
(packet listener事件监听,而packet collector是一个packets的可以进行polling和blocking操作的结果集队列。)
So, a packet listener is useful when you want to take some action whenever a packet happens to come in, while a packet collector is useful when you want to wait for a specific packet to arrive.
(packet listener一旦数据包传递抵达的时候你可以进行处理,packet collector则被使用在你需要等待一个指定的packet传递抵达时候。)
Packet collectors and listeners can be created using an Connection instance.
(packet listener和packet collector在connection实例中被创建。)
// Create a packet filter to listen for new messages from a particular
// user. We use an AndFilter to combine two other filters._
PacketFilter filter = new AndFilter(new PacketTypeFilter(Message.class),
newFromContainsFilter("mary@jivesoftware.com"));
// Assume we've created a XMPPConnection name "connection".
// First, register a packet collector using the filter we created.
PacketCollectormyCollector = connection.createPacketCollector(filter);
// Normally, you'd do something with the collector, like wait for new packets.
// Next, create a packet listener. We use an anonymous inner class for brevity.
PacketListenermyListener = new PacketListener() {
public void processPacket(Packet packet) {
// Do something with the incoming packet here._
}
};
// Register the listener._
connection.addPacketListener(myListener, filter);
Managing Connection
Connect and disConnect
// Create the configuration for this new connection_
ConnectionConfigurationconfig = new ConnectionConfiguration("jabber.org", 5222);
AbstractXMPPConnection connection = new XMPPTCPConnection(config);
// Connect to the server_
connection.connect();
// Log into the server_
connection.login("username", "password", "SomeResource");
...
// Disconnect from the server_
connection.disconnect();
Messaging using Chat
Chat
org.jivesoftware.smack.Chat
// Assume we've created a XMPPConnection name "connection"._
ChatManagerchatmanager = connection.getChatManager();
Chat newChat = chatmanager.createChat("jsmith@jivesoftware.com", new MessageListener() {
public void processMessage(Chat chat, Message message) {
System.out.println("Received message: " + message);
}
});
try {
newChat.sendMessage("Howdy!");
}
catch (XMPPException e) {
System.out.println("Error Delivering block");
}
Message newMessage = new Message();
newMessage.setBody("Howdy!");
message.setProperty("favoriteColor", "red");
newChat.sendMessage(newMessage);
// Assume a MessageListener we've setup with a chat._
public void processMessage(Chat chat, Message message) {
// Send back the same text the other user sent us._
chat.sendMessage(message.getBody());
}
incoming Chat
_// Assume we've created a XMPPConnection name "connection"._
ChatManagerchatmanager = connection.getChatManager().addChatListener(
newChatManagerListener() {
@Override
public void chatCreated(Chat chat, booleancreatedLocally)
{
if (!createdLocally)
chat.addMessageListener(new MyNewMessageListener());;
}
});
Roster and Presence
roster entries
包含xmpp地址,备注名,群组(假如该用户不属于任何一组,则调用“unfiled entry”):
Roster roster = connection.getRoster();
Collection
for (RosterEntry entry : entries) {
System.out.println(entry);
}
监听roster和presence更改:
Roster roster = con.getRoster();
roster.addRosterListener(new RosterListener() {
// Ignored events public void entriesAdded(Collection
public void entriesDeleted(Collection
public void entriesUpdated(Collection
public void presenceChanged(Presence presence) {
System.out.println("Presence changed: " + presence.getFrom() + " " + presence);
}
});
Provider architecture
smack provider是用于解析packet extension 和 IQ xml流的,有两种类型的provider:
IQProvider -parses IQ request into java objects
Extension Provider - parses XML sub-documents attached to packets into PacketExtension instances. By default, Smack only knows how to process a few standard packets and sub-packets that are in a few namespaces such as:
(解析packet的xml子元素到PacketExtension实例中。Smack默认仅知道处理少数的标准packets和少数的指定的namespaces下的子packets)

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Diffusion can not only imitate better, but also "create". The diffusion model (DiffusionModel) is an image generation model. Compared with the well-known algorithms such as GAN and VAE in the field of AI, the diffusion model takes a different approach. Its main idea is a process of first adding noise to the image and then gradually denoising it. How to denoise and restore the original image is the core part of the algorithm. The final algorithm is able to generate an image from a random noisy image. In recent years, the phenomenal growth of generative AI has enabled many exciting applications in text-to-image generation, video generation, and more. The basic principle behind these generative tools is the concept of diffusion, a special sampling mechanism that overcomes the limitations of previous methods.

Kimi: In just one sentence, in just ten seconds, a PPT will be ready. PPT is so annoying! To hold a meeting, you need to have a PPT; to write a weekly report, you need to have a PPT; to make an investment, you need to show a PPT; even when you accuse someone of cheating, you have to send a PPT. College is more like studying a PPT major. You watch PPT in class and do PPT after class. Perhaps, when Dennis Austin invented PPT 37 years ago, he did not expect that one day PPT would become so widespread. Talking about our hard experience of making PPT brings tears to our eyes. "It took three months to make a PPT of more than 20 pages, and I revised it dozens of times. I felt like vomiting when I saw the PPT." "At my peak, I did five PPTs a day, and even my breathing was PPT." If you have an impromptu meeting, you should do it

In the early morning of June 20th, Beijing time, CVPR2024, the top international computer vision conference held in Seattle, officially announced the best paper and other awards. This year, a total of 10 papers won awards, including 2 best papers and 2 best student papers. In addition, there were 2 best paper nominations and 4 best student paper nominations. The top conference in the field of computer vision (CV) is CVPR, which attracts a large number of research institutions and universities every year. According to statistics, a total of 11,532 papers were submitted this year, and 2,719 were accepted, with an acceptance rate of 23.6%. According to Georgia Institute of Technology’s statistical analysis of CVPR2024 data, from the perspective of research topics, the largest number of papers is image and video synthesis and generation (Imageandvideosyn

As a widely used programming language, C language is one of the basic languages that must be learned for those who want to engage in computer programming. However, for beginners, learning a new programming language can be difficult, especially due to the lack of relevant learning tools and teaching materials. In this article, I will introduce five programming software to help beginners get started with C language and help you get started quickly. The first programming software was Code::Blocks. Code::Blocks is a free, open source integrated development environment (IDE) for

Title: A must-read for technical beginners: Difficulty analysis of C language and Python, requiring specific code examples In today's digital age, programming technology has become an increasingly important ability. Whether you want to work in fields such as software development, data analysis, artificial intelligence, or just learn programming out of interest, choosing a suitable programming language is the first step. Among many programming languages, C language and Python are two widely used programming languages, each with its own characteristics. This article will analyze the difficulty levels of C language and Python

We know that LLM is trained on large-scale computer clusters using massive data. This site has introduced many methods and technologies used to assist and improve the LLM training process. Today, what we want to share is an article that goes deep into the underlying technology and introduces how to turn a bunch of "bare metals" without even an operating system into a computer cluster for training LLM. This article comes from Imbue, an AI startup that strives to achieve general intelligence by understanding how machines think. Of course, turning a bunch of "bare metal" without an operating system into a computer cluster for training LLM is not an easy process, full of exploration and trial and error, but Imbue finally successfully trained an LLM with 70 billion parameters. and in the process accumulate

Many gamers have encountered the frustrating issue of the game failing to initialize the graphics system. This article will delve into the common reasons behind this problem and find simple yet effective solutions that will get you back on the board and beating the level in no time. So, if you are getting Unable to initialize graphics system error message in Rollercoaster Tycoon, Assassin’s Creed, Tony Hawk’s Pro Skater, etc., then follow the solutions mentioned in this article. Initialization error Unable to initialize the graphics system. Graphics cards are not supported. Fix the Unable to initialize the graphics system error message To resolve the Unable to initialize the graphics system error in games like Rollercoaster Tycoon, Assassin's Creed, Tony Hawk's Pro Skater, etc., you can try the following workarounds: Update your graphics card driver in Compatibility Mode

Editor of the Machine Power Report: Yang Wen The wave of artificial intelligence represented by large models and AIGC has been quietly changing the way we live and work, but most people still don’t know how to use it. Therefore, we have launched the "AI in Use" column to introduce in detail how to use AI through intuitive, interesting and concise artificial intelligence use cases and stimulate everyone's thinking. We also welcome readers to submit innovative, hands-on use cases. Video link: https://mp.weixin.qq.com/s/2hX_i7li3RqdE4u016yGhQ Recently, the life vlog of a girl living alone became popular on Xiaohongshu. An illustration-style animation, coupled with a few healing words, can be easily picked up in just a few days.
