Solved

Problem using datagramSocket in Java

Posted on 2010-08-17
7
992 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 
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

What Is Transaction Monitoring and who needs it?

Synthetic Transaction Monitoring that you need for the day to day, which ensures your business website keeps running optimally, and that there is no downtime to impact your customer experience.

Question has a verified solution.

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

Here is a helpful source code for C++ Builder programmers that allows you to manage and manipulate HTML content from C++ code, while also handling HTML events like onclick, onmouseover, ... Some objects defined and used in this source include: …
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

717 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