【问题标题】:Peer-to-Peer Messenger点对点信使
【发布时间】:2016-10-07 12:19:51
【问题描述】:

我正在尝试使用套接字编写桌面聊天应用程序,我的目的是创建一个在客户端之间使用对等通信的消息传递系统。

如果我有目标收件人的 IP 地址,我可以直接连接到客户端而不必担心中间服务器吗?

如果有人能帮助我指出正确的方向,我将不胜感激。

【问题讨论】:

  • 简短的回答是肯定的。您应该能够直接连接到任何外部 IP 地址,因为它没有被防火墙阻止或连接不良。如果您只需要点对点通信,而不是群信使,那么使用基本套接字应该很容易编写。
  • 听起来像是 websockets 的东西。我认为javax.websocket 包使用起来非常简单。这可能会有所帮助:stackoverflow.com/questions/26452903/…

标签: java sockets p2p


【解决方案1】:

是的,如果您知道收件人的地址是什么,这很容易。只需通过连接以纯文本形式发送消息,用换行符、空终止符分隔,在实际文本之前写入消息长度等。
这是客户端网络的示例类:

import java.net.Socket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;

public class Networker{
    private Socket conn;

    public void connectTo(InetAddress addr)throws IOException{
        conn = new Socket(addr, 8989); //Second argument is the port you want to use for your chat
        conn.setSoTimeout(5); //How much time receiveMessage() waits for messages before it exits
    }

    public void sendMessage(String message)throws IOException{
        //Here I put one byte indicating the length of the message at the beginning
        //Get the length of the string
        int length = message.length();

        //Because we are using one byte to tell the server our message length,
        //we cap it to 255(max value an UNSIGNED byte can hold)
        if(length > 255)
            length = 255;

        OutputStream os = conn.getOutputStream();
        os.write(length);
        os.write(message.getBytes(), 0, length);
    }

    //Checks if a message is available
    //Should be called periodically
    public String receiveMessage()throws IOException{
        try{
            InputStream is = conn.getInputStream();

            int length = is.read();

            //Allocate a new buffer to store what we received
            byte[] buf = new byte[length];

            //The data received may be smaller than specified
            length = is.read(buf);

            return new String(buf, 0, length);
        }catch(SocketTimeoutException e){} //Nothing special,
        //There was just no data available when we tried to read a message
        return null;
    }
}

不过,我听说有些防火墙会阻止传入连接,在这种情况下,您必须使用 UDP。它的问题在于它不可靠(也就是说,如果您只是发送消息,它们可能不会到达目的地)

在我看来,P2P 的真正问题是找到对等点(实际上,只需要一个,因为之后我们的新对等点会告诉我们它的对等点,而这些对等点会告诉我们它们的对等点,等等)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 2019-09-15
    • 1970-01-01
    • 2019-06-11
    • 2021-05-08
    • 2016-07-13
    • 1970-01-01
    相关资源
    最近更新 更多