使用套接字和XMPP发送消息

时间:2019-04-16 16:18:19

标签: java sockets xmpp

我正在学习Java套接字,并且想尝试仅使用套接字来实现XMPP库,但是我不知道该怎么做。我读过RFC,但一无所知。

我想实现这些功能:

  • 发送/接收消息
  • 用户状态
  • 所有联系人

据我所知,这意味着我可以成功地继续向服务器发送消息,但是如何?

public static void main(String[] args) {
        String connect = "<?xml version='1.0'?> "
                + "<stream:stream "
                + "to='jabber.ru' version='1.0' "
                + "xmlns='jabber:client' "
                + "xmlns:stream='http://etherx.jabber.org/streams'>";

        String msg = "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\">";

        try {
            InetAddress address = InetAddress.getByName(host);
            Socket socket = new Socket(address, port);
            socket.setKeepAlive(true);

            OutputStream os = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os);
            BufferedWriter bw = new BufferedWriter(osw);
            bw.write(connect);
            bw.flush();
            System.out.println("Message sent to the server : " + connect);

            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String message = br.readLine();
            System.out.println("Message received from the server : " + message);

            bw.write(msg);
            bw.flush();
            System.out.println("Message sent to the server : " + msg);

            is = socket.getInputStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            message = br.readLine();
            System.out.println("Message received from the server : " + message);

        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

注意:我不想使用任何库!因此Smack和其他人没有帮助。

1 个答案:

答案 0 :(得分:0)

在收到切换到TLS的确认后,您需要将套接字切换到TLS,并且不再使用明文。完成后,您只需打开流并开始协商序列即可。服务器将发送您的流功能,并且您将能够进行身份验证。