带有 StremSocket 的 C# XMPP 在资源绑定后挂起
C# XMPP with StremSocket hangs after resource binding
我需要在 C# 中为 UWP 应用构建 XMPP 客户端。
我知道有一些 .NET 库,但似乎效果不是很好(免费的),所以我决定自己实现它。
服务器端是一个ejabberd服务。
我以这种方式使用 StreamSocket(参考 XMPP 3920bis):
StreamSocket socket = new StreamSocket();
await socket.ConnectAsync(new HostName("my.server.com"), "5222", SocketProtectionLevel.PlainSocket);
DataWriter dw = new DataWriter(socket.OutputStream);
DataReader dr = new DataReader(socket.InputStream);
dr.InputStreamOptions = InputStreamOptions.Partial;
// Open stream
await XmppWrite("<?xml version='1.0'?><stream:stream to='my.server.com' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>", dw);
var resp = await XmppRead(dr);
// Auth
var sasl = Base64Encode('[=10=]' + SaslPrep("username") + '[=10=]' + SaslPrep("password"));
await XmppWrite("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>" + sasl + "</auth>", dw);
resp = await XmppRead(dr);
// Request bind
await XmppWrite("<?xml version='1.0'?><stream:stream to='my.server.com' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>", dw);
resp = await XmppRead(dr);
// Resource binding
await XmppWrite("<iq id='"+ObtainID()+"' type='set'><bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'/></iq>", dw);
resp = await XmppRead(dr);
// Send initial presence
await XmppWrite("<presence/>", dw);
resp = await XmppRead(dr);
一切正常,直到我发送初始状态,服务器没有响应并且连接已关闭。
有什么想法吗?
问题出在资源绑定后缺少的步骤 "open session"。
// Resource binding
await XmppWrite("<iq id='"+ObtainID()+"' type='set'><bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'/></iq>", dw);
resp = await XmppRead(dr);
// Open session
await XmppWrite("<iq id='" + Guid.NewGuid() + "' type='set'><session xmlns='urn:ietf:params:xml:ns:xmpp-session'/></iq>", dw);
resp = await XmppRead(dr);
// Send initial presence
await XmppWrite("<presence/>", dw);
resp = await XmppRead(dr);