Solved

Problem using datagramSocket in Java

Posted on 2010-08-17
7
961 Views
Last Modified: 2013-12-15
Dear Expert:

I'm developing a little application that use DatagramSocket and DatagramPacket classes in Java. The program takes 3 command line parameters: host, port and message, and sends the message to a server (host) on the port specified. Server reads the message, transform it to uppercase and sends back message to client.

When I execute client (with server running on other session) it raises a run-time error telling length or index is wrong. There are two println: only first println is executed so I know the line is failing but not why. Could you help me ?

I attach the code of the client. I could attach also the code of the server if you need it.

Thank you.
import java.net.*;

public class Client {
	public static void main(String args[]){
		DatagramSocket dg;
		DatagramPacket p;
		InetAddress iaddr;
		int portRemot;
		String host, missatge;
		byte buf [];
		
		buf = new byte[100];
		host = args[0];
		portRemot = Integer.parseInt(args[1]);
		missatge = args[2];
		try {
			dg = new DatagramSocket();
			iaddr =  InetAddress.getByName(null);
			buf = missatge.getBytes();
System.out.println("point 1");
			p = new DatagramPacket(buf, 100, iaddr, portRemot);
System.out.println("point 2");
			dg.send(p);
			dg.receive(p);
			buf = p.getData();
			missatge = new String(buf);
			System.out.println(missatge);
			dg.close();		
		} catch(Exception e) { System.out.println(e.getMessage()); }
	}
}

Open in new window

0
Comment
Question by:gplana
  • 4
  • 3
7 Comments
 
LVL 7

Expert Comment

by:HalfAsleep
ID: 33458496
Could you provide the runtime error message?

Also, your code will be more robust if you check the size of args, maybe not assume that all arguments will be there.

If size of args is less than the minimun required, you could print a "usage" text before exiting.

Also, according to the Java documentation, the length argument must be less than or equal to buf.length.  It seems you are in the clear, but for fun, try to create the buffer with one more byte and see if that was your problem.
0
 
LVL 15

Author Comment

by:gplana
ID: 33458583
I call by>
java Client localhost 23000 Hi
 
This is the server code. If you compile both and call Server by
java Servidor 23000
you will see Client print "point 1" but not "point 2".
The runtime error message is> "illegal length or offset"
 
0
 
LVL 15

Author Comment

by:gplana
ID: 33458595
Sorry, I forget the server code:

import java.net.*;

public class Client {
    public static void main(String args[]){
        DatagramSocket dg;
        DatagramPacket p;
        InetAddress iaddr;
        int portRemot;
        String host, missatge;
        byte buf [];
       
        buf = new byte[100];
        host = args[0];
        portRemot = Integer.parseInt(args[1]);
        missatge = args[2];
        try {
            dg = new DatagramSocket();
            iaddr =  InetAddress.getByName(null);
            buf = missatge.getBytes();
System.out.println("point 1");
            p = new DatagramPacket(buf, 100, iaddr, portRemot);
System.out.println("point 2");
            dg.send(p);
            dg.receive(p);
            buf = p.getData();
            missatge = new String(buf);
            System.out.println(missatge);
            dg.close();        
        } catch(Exception e) { System.out.println(e.getMessage()); }
    }
}
0
Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

 
LVL 7

Accepted Solution

by:
HalfAsleep earned 500 total points
ID: 33458954
I do not have a java environment to try this out on right now.  

The line
p = new DatagramPacket(buf, 100, iaddr, portRemot);

looks slightly erroneous.  you do not want to send the entire buf, only the parts of buf in use.

How about something like
p = new DatagramPacket(buf, missatge.length(), iaddr, portRemot);

Also, try to make sure buf.length is at least one larger than the length parameter to the constructor.
0
 
LVL 15

Author Comment

by:gplana
ID: 33459202
Excellent. This was the problem !!!
I tried to put mssatge.length() instead of 100 and it works now. But what I don't understand is why it oesn't work if I put missatge.length()+1. I haven't to send the mark of the end of the string (0 character) ?
And if I put some non-english characters the program doesn't finalize. I suppose because strings in java would be UTF-8 encoded, which encodes non-english characters in 2 bytes. So how can I get the number of bytes instead of the number ofcharacters ?
0
 
LVL 7

Expert Comment

by:HalfAsleep
ID: 33459320
If you want to know how many bytes the string turns into, you can try this>

int numBytes = myString.getBytes().length;
0
 
LVL 15

Author Comment

by:gplana
ID: 33459396
Excellent. Thank you.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Update (December 2011): Since this article was published, the things have changed for good for Android native developers. The Sequoyah Project (http://www.eclipse.org/sequoyah/) automates most of the tasks discussed in this article. You can even fin…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
The viewer will learn how to use and create keystrokes in Netbeans IDE 8.0 for Windows.

856 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question