我正在尝试使用套接字编写桌面聊天应用程序,我的目的是创建一个使用客户端之间的对等通信的消息传递系统。
如果我有目标收件人的IP地址,我可以直接连接到客户端而不必担心中间服务器吗?
如果有人能帮我指出正确的方向,我会非常感激。
答案 0 :(得分:0)
是的,如果你知道收件人的地址是什么,这很容易。只需在连接上以纯文本形式发送消息,用新行,空终止符分隔,在实际文本之前写入消息长度等。
以下是客户端网络的示例类:
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的真正问题在于找到同行(真的,只有一个是必要的,因为之后我们的新同行会告诉我们有关同行的信息,以及那些同行关于他们的同行等等)