gpt4 book ai didi

java - 点对点信使

转载 作者:太空宇宙 更新时间:2023-11-04 12:32:39 25 4
gpt4 key购买 nike

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

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

如果有人能帮助我指明正确的方向,我将非常感激。

最佳答案

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

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 的真正问题是找到对等点(实际上,只有一个是必要的,因为之后我们的新对等点将告诉我们有关其对等点的信息,以及这些对等点有关其对等点的信息,等等)

关于java - 点对点信使,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37682036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com