Why I am getting the bad length exception when I am running this application? - java-me

I want to communicate to a server from J2me app using UDP.However, when I am running the app, I am getting a bad length exception.My codes and output are given below.
client code
import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;
import java.io.IOException;
public class DatagramTest extends MIDlet
implements CommandListener, Runnable
{
private static final int BUF_SIZE = 1024;
private static Command exit = new Command("Exit", Command.EXIT, 1);
private static DatagramTest instance;
private Display display;
private TextBox dgramText;
private DatagramConnection conn;
private Datagram dgram;
private String address = "datagram://myip:9876";
public DatagramTest()
{
super();
instance = this;
}
public DatagramTest(String service)
{
this();
address = service;
}
/**
Returns the single instance of this class. Calling
this method before constructing an object will return
a null pointer.
#return an instance of this class.
*/
public static DatagramTest getInstance()
{
return instance;
}
public void startApp()
{
display = Display.getDisplay(this);
dgramText = new TextBox("Datagram contents",
null,
2048,
TextField.ANY);
dgramText.setCommandListener(this);
display.setCurrent(dgramText);
System.out.println("Starting run....");
run();
System.out.println("Stopping run....");
}
public void run()
{
System.out.println("In run....");
try
{
int maxLength;
conn = (DatagramConnection)Connector.open(address);
maxLength = conn.getMaximumLength();
dgram = conn.newDatagram(1024);
dgram.reset();
conn.send(dgram);
conn.receive(dgram);
byte[] data = dgram.getData();
// Extract the response string.
String str = new String(data);
System.out.println(str);
dgram.reset();
System.out.println("Exit run....");
}
catch (IOException ioe)
{
System.out.println(ioe.getMessage());
ioe.printStackTrace();
quit();
}
return;
}
public void pauseApp()
{
}
void quit()
{
destroyApp(true);
notifyDestroyed();
}
public void destroyApp(boolean destroy)
{
try
{
conn.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
public void display()
{
Display.getDisplay(this).setCurrent(dgramText);
}
public void commandAction(Command c, Displayable d)
{
if (c == exit)
{
quit();
}
}
}
Server code
import java.io.*;
import java.net.*;
class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
Output at clientside
Starting run.... In run.... Bad
datagram length java.io.IOException:
Bad datagram length
at com.sun.midp.io.j2me.datagram.Protocol.receive(Protocol.java:367)
at hello.DatagramTest.run(DatagramTest.java:89)
at hello.DatagramTest.startApp(DatagramTest.java:69)
at javax.microedition.midlet.MIDletProxy.startApp(MIDletProxy.java:43)
at com.sun.midp.midlet.Scheduler.schedule(Scheduler.java:374)
at com.sun.midp.main.Main.runLocalClass(Main.java:466)
at com.sun.midp.main.Main.main(Main.java:120)
Stopping run....
Why I am getting this bad length exception and how do I sort it out?

One thing you need to try is to send and receive datagrams in a separate thread.
The documentation for DatagramConnection.receive() says: "This method blocks until a datagram is received"
You are calling it from inside MIDlet.startApp().
Blocking the application management system thread that calls startApp() is bad practice.

Related

Live Streaming audio from java server to Android Client

I want to stream audio from my computer to android clients. I have taken the input and now I want that to be transmitted over the stream and be played. Now my problem is that on the input side I have AudioInputStream class and other classes which I am able to use but on the android side it says that they are private and cannot be accessed outside the class. I want to play the coming audio on android. What should I do. I just want to support 1 client for now.
Server:
import java.net.*;
import java.io.*;
import javax.sound.sampled.*;
public class MainServer{
private static AudioFormat getAudioFormat() {
AudioFormat.Encoding encoding = AudioFormat.Encoding.PCM_SIGNED;
float rate = 44100.0f;
int channels = 2;
int sampleSize = 16;
boolean bigEndian = true;
InetAddress addr;
AudioFormat format = new AudioFormat(encoding, rate, sampleSize, channels, (sampleSize / 8) * channels, rate, bigEndian);
return format;
}
private static TargetDataLine configureStreams(){
try{
AudioFormat format = getAudioFormat();
DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
// checks if system supports the data line
if (!AudioSystem.isLineSupported(info)) {
System.out.println("Line not supported");
System.exit(0);
}
TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
line.open(format);
line.start();
System.out.println("Got the line and started to listen");
return line;
}
catch(Exception e){
System.err.println(e);
}
return null;
}
public static void main(String args[]){
try{
ServerSocket server = new ServerSocket(3000);
System.out.println("Server is listening");
TargetDataLine audio = configureStreams();
while(true){
Socket socket = server.accept();
System.out.println("Current accepted socket: "+socket);
HandlingClient client = new HandlingClient(socket, audio);
client.start();
}
}
catch(Exception e){
System.err.println(e);
}
}
}
class HandlingClient extends Thread{
AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;
private Socket socket;
private OutputStream output;
private TargetDataLine audio;
HandlingClient(Socket socket, TargetDataLine audio){
this.socket=socket;
this.audio=audio;
}
public void run(){
try{
AudioInputStream ais = new AudioInputStream(audio);
output=socket.getOutputStream();
byte[]data = new byte[1024];
System.out.println("Start recording and sending");
while(true){
data=ais.readNBytes(1024);
output.write(data);
}
}
catch(Exception e){
System.err.println(e);
System.out.println("OutputStream: "+output);
System.out.println("Socket: "+socket);
}
}
}
Android Client:
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.EditText;
import java.io.IOException;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy myCustomizableThread = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(myCustomizableThread);
//Starting from here
}
public void connect(View view){
final EditText editText = findViewById(R.id.url);
String url = editText.getText().toString().trim(); //User enters the url in the form like 192.168.43.102:3000
String target = url.substring(0, url.indexOf(':'));
int port = Integer.parseInt(url.substring(url.indexOf(':')+1, url.length()));
try {
Socket socket = new Socket(target, port);
//Media player here to play the recording
} catch (IOException e) {
e.printStackTrace();
}
}
}

j2me sprite not working

First, I'm sorry for my bad English. I'm a newbie J2ME
I wrote the below code after i watched some tutorial but it not working. I don't know what happen with it.
AnimationCanvas.java
package example;
import java.io.IOException;
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.lcdui.game.LayerManager;
import javax.microedition.lcdui.game.Sprite;
public class AnimationCanvas extends GameCanvas implements Runnable {
private Sprite ca;
private int frameWidth = 14;
private int frameHeight = 14;
private boolean playing = true;
private int a=1;
public AnimationCanvas(){
super(true);
try {
ca = new Sprite(Image.createImage("ca.png"), frameWidth, frameHeight);
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void start() {
Thread runner = new Thread(this);
runner.start();
}
public void run(){
while (playing){
drawDisplay(getGraphics());
try{
Thread.sleep(10);
} catch(Exception e){}
}
}
public void drawDisplay(Graphics g){
g.setColor(0x000000);
g.fillRect(0,0,getWidth(),getHeight());
ca.setFrame(1);
ca.paint(g);
flushGraphics();
}
public void stop(){
playing=false;
}
}
and AnimationMidlet.java
package example;
import java.io.IOException;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class AnimationMidlet extends MIDlet {
private Display display;
private AnimationCanvas canvas;
public AnimationMidlet() throws IOException {
display = Display.getDisplay(this);
canvas = new AnimationCanvas();
}
private void initialize() {
// write pre-initialize user code here
// write post-initialize user code here
}
public void startMIDlet() {
// write pre-action user code here
// write post-action user code here
}
public void resumeMIDlet() {
// write pre-action user code here
// write post-action user code here
}
public void switchDisplayable(Alert alert, Displayable nextDisplayable) {
// write pre-switch user code here
Display display = getDisplay();
if (alert == null) {
display.setCurrent(nextDisplayable);
} else {
display.setCurrent(alert, nextDisplayable);
}
// write post-switch user code here
}
public Display getDisplay() {
return Display.getDisplay(this);
}
public void startApp() {
if(canvas!=null){
display.setCurrent(canvas);
canvas.start();
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
canvas.stop();
}
}
and the output
Running in the identified_third_party security domain
java.io.IOException
Uncaught exception java/lang/NullPointerException.
at javax.microedition.lcdui.ImmutableImage.getImageFromStream(Image.java:968)
at javax.microedition.lcdui.ImmutableImage.(Image.java:939)
at javax.microedition.lcdui.Image.createImage(Image.java:313)
at example.AnimationCanvas.(AnimationCanvas.java:25)
at example.AnimationMidlet.(AnimationMidlet.java:25)
at java.lang.Class.runCustomCode(+0)
at com.sun.midp.midlet.MIDletState.createMIDlet(+34)
Thanks for your reading!

How could I turn this into a thread so it doesn't freeze up my app?

So I was wanting to know how I would go about turning this into a thread? I have tried and failed multiple times. I am about read to give up and just deal with the application freezing while it gets a response.
package me.robert.tb.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class HTTPConnect {
private static BufferedReader reader = null;
private static StringBuilder buffer = new StringBuilder();
/**
* This method is used to connect to a website and return its response.
* Mainly used for connecting to API's
*
* #param link
* The URL of the website
* #return The response from the website
*/
public static String getResponse(String link) {
try {
reader = new BufferedReader(new InputStreamReader(new URL(link).openStream()));
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
} catch (Exception e) {
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException e) {
}
}
return buffer.toString();
}
}
Any help is greatly appreciated!
Here you go. Though you shouldn't really need threads to import 1024 characters. On a few test pages it ran pretty quickly. I think your main issue is trying to make getResponse() static. Anyway, here's your modified code using a thread.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class HTTPConnect implements Runnable{
private static BufferedReader reader = null;
private static StringBuilder buffer = new StringBuilder();
private String link;
private String response;
/**
* This method is used to connect to a website and return its response.
* Mainly used for connecting to API's
*
* #param link
* The URL of the website
* #return The response from the website
*/
public HTTPConnect(String input){
link = input;
}
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(new URL(link).openStream()));
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
} catch (Exception e) {
} finally {
try {
if (reader != null)
reader.close();
response = buffer.toString();
} catch (IOException e) {
}
}
}
public String getResponse(){
return response;
}
public static void main (String[] args){
String website = "http://google.com";
Thread t = new Thread(new HTTPConnect(website));
t.run();
}
}

how to convert thread to multi thread?

I want to the following code to convert the thread to newFixedThreadpool()
how do I do it?
//saddddddddddddddddddddddddddddffgfggggggggggggggggggggggggfdhfdhfdhdhdfhjhljgjhgdadsadsafds
class client :
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Arrays;
import java.lang.*;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws Exception {
String fileName = null;
try {
fileName = args[0];
} catch (Exception e) {
System.out.println("Enter the name of the file :");
Scanner scanner = new Scanner(System.in);
String file_name = scanner.nextLine();
File file = new File(file_name);
Socket socket = new Socket("localhost", 3332);
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(file.getName());
FileInputStream fis = new FileInputStream(file);
byte [] buffer = new byte[Server.BUFFER_SIZE];
Integer bytesRead = 0;
while ((bytesRead = fis.read(buffer)) > 0) {
oos.writeObject(bytesRead);
oos.writeObject(Arrays.copyOf(buffer, buffer.length));
}
oos.close();
ois.close();
System.exit(0);
}
}
}
class server:
import java.io.FileOutputStream;
import java.io.*;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server extends Thread {
public static final int PORT = 3332;
public static final int BUFFER_SIZE = 100;
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
while (true) {
Socket s = serverSocket.accept();
saveFile(s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveFile(Socket socket) throws Exception {
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
FileOutputStream fos = null;
byte [] buffer = new byte[BUFFER_SIZE];
Object o = ois.readObject();
if (o instanceof String) {
fos = new FileOutputStream(new File("/home/reza/Desktop/reza"));
} else {
throwException("Something is wrong");
}
Integer bytesRead = 0;
do {
o = ois.readObject();
if (!(o instanceof Integer)) {
throwException("Something is wrong");
}
bytesRead = (Integer)o;
o = ois.readObject();
if (!(o instanceof byte[])) {
throwException("Something is wrong");
}
buffer = (byte[])o;
fos.write(buffer, 0, bytesRead);
} while (bytesRead == BUFFER_SIZE);
System.out.println("File transfer success");
fos.close();
ois.close();
oos.close();
}
public static void throwException(String message) throws Exception {
throw new Exception(message);
}
public static void main(String[] args) {
new Server().start();
}
}
public class Server extends Thread {
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
while (true) {
Socket s = serverSocket.accept();
new ServerWorker(s).start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class ServerWorker extends Thread {
private Socket _socket;
public ServerWorker(Socket socket) {
this._socket = socket;
}
public void run() {
saveFile(this._socket);
// Thread should terminate when run returns.
}
private void saveFile(Socket socket) throws Exception {
...
}
}

error in java code (j2me)

I am getting an exception for the following code. I am not able to understand what is UUID. Can anyone help to resolve this error? I have posted the code as well as error I am getting.
package wiki.nokia.example;
import java.io.IOException;
import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.L2CAPConnection;
import javax.bluetooth.L2CAPConnectionNotifier;
import javax.bluetooth.LocalDevice;
import javax.microedition.io.Connector;
public class BluetoothServer implements Runnable {
private boolean listening = true;
private LocalDevice local_device;
private BtoothChat midlet;
private String deviceName;
private L2CAPConnection con;
/** Creates a new instance of BluetoothServer */
public BluetoothServer(BtoothChat midlet) {
this.midlet = midlet;
Thread t = new Thread(this);
t.start();
}
public void run(){
System.out.println("Starting server - please wait...");
try {
local_device = LocalDevice.getLocalDevice();
DiscoveryAgent disc_agent = local_device.getDiscoveryAgent();
local_device.setDiscoverable(DiscoveryAgent.LIAC);
String service_UUID = "9";
deviceName = local_device.getFriendlyName();
String url = "btl2cap://localhost:" + service_UUID + ";name=" + deviceName;
L2CAPConnectionNotifier notifier = (L2CAPConnectionNotifier)Connector.open(url);
con = notifier.acceptAndOpen();
while (listening) {
if (con.ready()){
byte[] b = new byte[1000];
con.receive(b);
String s = new String(b, 0, b.length);
System.out.println("Recieved from client: " + s.trim());
midlet.setAlert(s.trim());
send("Hello client, my name is: " + getName());
listening=false;
}
}
} catch(BluetoothStateException e){System.out.println(e);} catch(IOException f){System.out.println(f);}
}
private void send(String s){
byte[] b = s.getBytes();
try {
con.send(b);
} catch(IOException e){
System.out.println(e);
}
}
private String getName(){
return deviceName;
}
}
ERROR IS:
Starting server - please wait...
Uncaught exception: java.lang.NumberFormatException
at java.lang.Long.parseLong(Long.java:401)
at javax.bluetooth.UUID.<init>(), bci=166
at com.sun.jsr082.bluetooth.btl2cap.L2CAPNotifierImpl.createServiceRecord(), bci=26
at com.sun.jsr082.bluetooth.btl2cap.L2CAPNotifierImpl.<init>(), bci=122
at com.sun.jsr082.bluetooth.btl2cap.Protocol.serverConnection(), bci=16
at com.sun.jsr082.bluetooth.BluetoothProtocol.openPrimImpl(), bci=24
at com.sun.jsr082.bluetooth.BluetoothProtocol.openPrim(), bci=14
at com.sun.midp.io.j2me.btl2cap.Protocol.openPrim(), bci=7
at javax.microedition.io.Connector.openPrim(), bci=327
at javax.microedition.io.Connector.open(), bci=3
at javax.microedition.io.Connector.open(), bci=3
at javax.microedition.io.Connector.open(), bci=2
at wiki.nokia.example.BluetoothServer.run(BluetoothServer.java:48)
at java.lang.Thread.run(), bci=11
You can find a definition of an UUID here. The problem is that the UUID you are using isn't appropriate. A value of '9' won't do.

Resources