i just designed an application in Java to enable chat between multiple clients using one server. I used UDP sockets and multithreading. I had some questions about that:
Client side code:
private void sendMessage(String s) throws Exception
{
byte b[] = s.getBytes();
InetAddress address = InetAddress.getLocalHost();
DatagramPacket packet = new DatagramPacket(b, b.length, address, PORT);
socket.send(packet);
}
according to answer over here : (I hope i didnt misunderstand it) the getLocalHost() method should return the localhost loopback address. It however returns 192.xxx.xx.xx because I am connected to a network. Am I correct ?
My server side code to handle the sent packet is:
byte[] b = new byte[1024];
while (true)
{
try
{
Arrays.fill(b, (byte)0);
DatagramPacket packet = new DatagramPacket(b, b.length);
socket.receive(packet);
String content = new String(b, 0 , b.length);
InetAddress clientAddress = packet.getAddress();
int clientPort = packet.getPort();
String id = clientAddress.toString() + ":" + clientPort;
when I print id, it gives me : /192.168.56.1:64372 : GREETINGS
. But the port should be the one i sent the packet from the client side right ? If not, what am I doing wrong ? And finally, after some packets are sent, I get an exception : java.lang.StringIndexOutOfBoundsException: String index out of range: 1046
Is it because of the 1024 size byte array ? Thanks in advance :]