我正在尝试编写一个使用套接字的桌面聊天应用程序,我的目的是创建一个在客户端之间使用点对点通信的消息传递系统。
如果我有目标收件人的IP地址,我可以直接连接到客户端而不必担心中间服务器吗?
如果有人能帮我指明正确的方向,我将不胜感激。
发布于 2017-10-04 01:09:54
是的,如果你知道你的收件人的地址,这是相当容易的。只需在连接上以纯文本形式发送消息,由换行符、空终止符、在实际文本之前写入消息长度等分隔。
以下是客户端网络的示例类:
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的真正问题是找到同级(实际上,只有一个是必要的,因为在那之后,我们的新同级会告诉我们它的同级,以及那些同级的同级,等等)
https://stackoverflow.com/questions/37682036
复制相似问题