Reputation: 21
I'm attempting to write a desktop chat application using sockets and my intention is to create a messaging system that uses peer-to-peer communication between clients.
If I have the IP addresses of the intended recipients, can I connect to the client directly without having to worry about an intermediate server?
If anyone could help point me in the right direction I would really appreciate it.
Upvotes: 2
Views: 2351
Reputation: 94
Yes, if you know what are the addresses of your recipients this is pretty easy. Just send messages as plain text over the connection, separated by new line, null-terminator, write message length before the actual text, etc.
Here is an example class for the client networking:
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;
}
}
Although, I heard that some firewalls block incomming connections, in which case you have to use UDP. The problem with it, is that its unreliable(aka. if you just send messages, they might not arrive to the destanation)
The real problem with P2P in my oppinion is to find the peers(really, only one is neccessary, because after that our new peer will tell us about its peers, and those peers about their peers, and so on)
Upvotes: 1