Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Problem using datagramSocket in Java

Posted on 2010-08-17
7
Medium Priority
?
1,031 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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 7

Accepted Solution

by:
HalfAsleep earned 2000 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: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering 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

Jaspersoft Studio is a plugin for Eclipse that lets you create reports from a datasource.  In this article, we'll go over creating a report from a default template and setting up a datasource that connects to your database.
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
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 use NetBeans IDE 8.0 for Windows to connect to a MySQL database. Open Services Panel: Create a new connection using New Connection Wizard: Create a test database called eetutorial: Create a new test tabel called ee…
Suggested Courses

610 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