简体   繁体   中英

Multi threaded UDP socket programming in Java

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 :]

Ok you've got the Following Problems 1. The Receive Port is different 2. You get an IndexOutOfBounds Exception

To the first, I guess java is just reasigning that or your os, but anyway you receive it correctly!

To the second. You don't really know where the DatagramSocket stores your data! It might be anywere in your array, for that the packet safes the offset of your data and the length:

DatagramPacket p;
p.getLength()
p.getOffset()
p.getData()

So do it like this.

byte[] b = new byte[1024];
while (true) 
{
   try 
   {
      // This is not needed! Just check how much data you get
      // Arrays.fill(b, (byte)0);
      DatagramPacket packet = new DatagramPacket(b, b.length);
      socket.receive(packet);

      // This is the easiest
      String content = new String(packet.getData());

Still this is a bit strange because you already set all data to 0 and your not reading in more than 1024 = b.length bytes. But for data integrity defenitly use getData()!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM