Solved

Problem using datagramSocket in Java

Posted on 2010-08-17
7
916 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 7

Accepted Solution

by:
HalfAsleep earned 500 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Excellent. Thank you.
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
sumDigits  challenge 7 59
Change local server setting in php 6 58
recursion example 16 66
Groovy:unable to resolve class error 2 27
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
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…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
The viewer will learn how to synchronize PHP projects with a remote server in NetBeans IDE 8.0 for Windows.

763 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now