How to send string data to socket connection via telnet or any other program? - string

I am trying to send and receive string data to socket connection via telnet, but I am not able to type or see anything in the telnet window. I am able to connect to the server via telnet, but not able to send the string data.
Is there any other alternate method to send string data over socket connection.

Telnet, unless it negotiates parameters to the contrary, does "remote echo" meaning that you won't see anything you type unless the server echos it back.
A lot of people use the term "Telnet" when really it is a raw socket connection that does no configuration negotiation upon connect.
If you're sending data from a file or source other than the keyboard (and even often when sending from the keyboard), you're better of using a program like socket or nc (netcat) which don't attempt to do any processing of the data stream and so provide simple 8-bit clean connections.
In the case of both those problems, you can simply redirect stdin from a file or echo a string to them through a pipe.

i have a example of a server that talks to with many telnet client.
You must use the class DataInputStream and DataOutputStream
You must use A Class Implements Runnable for establish multiple sessions
You must use a ServerSocket Class.
Good, this is the code of the main class called SocketServerExample:
import java.net.*;
import java.io.*;
import socketserverexample.ThreadServer;
/**
*
* #author JuanLuisHiciano
*/
public class SocketServerExample {
public static void main(String args[]) throws InterruptedException {
ServerSocket mi_servicio = null;
String linea_recibida;
DataInputStream entrada = null;
DataOutputStream salida = null;
Socket socket_conectado = null;
try {
mi_servicio = new ServerSocket(2017);
}
catch (IOException excepcion) {
System.out.println(excepcion);
}
try {
int n=1;
while(n<2){
socket_conectado = mi_servicio.accept();
System.out.println("Un cliente se a conectado "+socket_conectado.getPort());
entrada= new DataInputStream(socket_conectado.getInputStream());
String nombre = entrada.readUTF();
// Se instancia una clase para atender al cliente y se lanza en
// un hilo aparte.
Runnable nuevoCliente = new ThreadServer(nombre, socket_conectado); //Input and Output data Channels
Thread hilo = new Thread(nuevoCliente);
hilo.start();
}
salida.writeUTF("Fin de la conexion....");
salida.close();
entrada.close();
socket_conectado.close();
}
catch (IOException excepcion) {
System.out.println(excepcion);
}
}
}
ok,This run de Main Server with the UTP port (2017) and delivering sessions to other threads to receive new connections.
Good , below is the code of the class Called ThreadServer :
import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author JuanLuisHiciano
*/
public class ThreadServer implements Runnable{
DataInputStream entrada;
DataOutputStream salida;
Socket socket_conectado = null;
String linea_recibida;
String cliente;
ThreadServer(String cliente,Socket socket) {
socket_conectado = socket;
this.cliente=cliente;
}
#Override
public void run() {
int n=0;
while(n<3){
try {
salida = new DataOutputStream(socket_conectado.getOutputStream());
entrada = new DataInputStream(socket_conectado.getInputStream());
//System.out.println("Confirmando Conexion al cliente .....");
salida.writeUTF("Conexion Exitosa\n");
salida.writeUTF("Puede compartir un mensaje : ");
//recepcion de mensaje
linea_recibida = entrada.readUTF();
System.out.println(cliente+" dice: "+linea_recibida);
System.out.println(socket_conectado.getPort());
n++;
} catch (IOException ex) {
Logger.getLogger(ThreadServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
With this code you can talk to each of the clients connecting.
Goodbye Saludos de Republica Dominicana
I hope you serve something this code.

Related

how to let the server forward received message from any client to all connected clients in java

I'm trying to make a chat system project (still incomplete) using java, but I need small help in forwarding the client's received message.
The server is working as multi-threading so many clients can connect to it, what I want is: (Assumed scenario) if 6 clients are connected to the server, then one of them send a message, it should be forwarded to all connected clients through the server.
here is the 2 codes..
Server side
import java.io.*;
import java.net.*;
public class ChatServer implements Runnable
{
Socket csocket;
ChatServer(Socket csocket){ this.csocket = csocket; }
public static void main(String[]args)throws Exception
{
ServerSocket sersock=new ServerSocket(3000);
System.out.println("Server ready for chatting");
while(true)
{
Socket sock =sersock.accept();
new Thread(new ChatServer(sock)).start();}
}
public void run()
{
try{
System.out.println(Thread.currentThread().getName() + ": HELLO");
BufferedReader keyRead=new BufferedReader(new InputStreamReader(System.in));
OutputStream ostream=csocket.getOutputStream();
PrintWriter pwrite=new PrintWriter(ostream, true);
InputStream istream=csocket.getInputStream();
BufferedReader receiveRead=new BufferedReader(new InputStreamReader(istream));
String receiveMessage, sendMessage;
while(true) {
if((receiveMessage=receiveRead.readLine())!=null)
{
System.out.print(Thread.currentThread().getName() + ": ");
if(receiveMessage.equals("QUIT"))
Thread.currentThread().stop();
else
System.out.println(receiveMessage);}
sendMessage=keyRead.readLine();
pwrite.println(sendMessage);
System.out.flush();}
} catch (IOException e){ System.out.println(e); }
}
}
client side
import java.io.*;
import java.net.*;
public class ChatClient
{
public static void main(String[]args)throws Exception
{
Socket sock =new Socket("localhost", 3000);
// reading from keyboard (keyRead object)
BufferedReader keyRead=new BufferedReader(new InputStreamReader(System.in));
// sending to client (pwrite object)
OutputStream ostream=sock.getOutputStream();
PrintWriter pwrite=new PrintWriter(ostream, true);
// receiving from server ( receiveRead object)
InputStream istream=sock.getInputStream();
BufferedReader receiveRead=new BufferedReader(new InputStreamReader(istream));
System.out.println("Start the chitchat, type and press Enter key");
String receiveMessage, sendMessage;
while(true)
{
sendMessage=keyRead.readLine();// keyboard reading
pwrite.println(sendMessage);// sending to server
System.out.flush();// flush the data
if((receiveMessage=receiveRead.readLine())!=null)//receive from server
{
System.out.println(receiveMessage);// displaying at DOS prompt
}
}
}
}
Thanks in advance.
I write these types of server applications frequently, as a way of connection client through a relay server when direct connections between them are not possible. The solution is simple, put each socket that you receive from the accept() function into a List or Tree of your choice.
List<Socket> connectionList = new ArrayList<Socket>();
...
Socket sock =sersock.accept();
connectionList.add(sock);
...
for (Socket connection : connectionList) {
connection.getOutputStream().write(msgBytes);
}

JavaFX, client GUI, 2 instances causes second socket to be NULL

I've coded a client program that communicates with my arduino server. It had a swing button and a methog that ran a loop checking for any input from the server. I tried it with multiple instances running from different or/and the same IP and everything was fine. Now I tried implementing that same method for the socket in a app with JavaFX GUI. After I read here and there that it needs to be on a separate thread I did it as instructed and it seems to be working just fine. If I try to launch a second instance of it though,it imidiately throws NullPointerException on the line where i check socket.isConnected() && !Socket.isClosed(). The first instance continues to work just fine, but the other one just stays with the GUI open.
As I've done it with the same class but not on a new thread and with swing button, I can say that the problem is not on the server side.
I need to be able to launch as many instances of the program as I want while they all keep an open socket at all times. Any ideas on how to fix that ?
Update: I tryed recalling the initiation in the loop when socket is lost. It seems that the socket closes right after it is opened.
Here is the Class for the client:
package panelSouth;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
public class Networking implements Runnable{
static Socket socket;
static OutputStreamWriter out;
public void run() {
//Initializing socket - IP/PORT
String host = "192.168.1.178";
int port = 2015;
boolean connected=true;
do{
try{
socket = new Socket(host,port);
}
catch(Exception unknownHostException){
connected=false;
System.out.println("Connecting to host...");
}
}while(connected==true);
System.out.println("Connection is a success!");
System.out.println("Requesting pin states...");
//Requesting pin states on startup.
try{
out = new OutputStreamWriter(socket.getOutputStream());
out.write("r;");
out.flush();
}catch(Exception ex){
System.out.println(ex);
}
listen();
}
//Listening for incoming commands from host
public static void listen(){
try{
BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream() ) );
while(socket.isConnected() && !socket.isClosed()){
States.commandProcess(in.readLine());
}
}catch(Exception ex){
System.out.println(ex);
}
}
//send commands.
static public void send(String command){
try{
out.write(command);
out.flush();
}catch(Exception ex){
System.out.println(ex);
}
}
//closing the socket and resetting the pins on host on close up.
static public void close(){
try{
OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream());
out.write("x;");
out.flush();
socket.close();
}catch(Exception exception){
}
}
}
And here is the Main:
public static void main(String[] args) throws Exception{
Thread network = new Thread(new Networking());
network.setDaemon(true);
network.start();
launch(args);
}
I removed the loops in the defining of the socket and I put recall of the function only in the catch{} part. It seems that the loop was defining more than one socket or something and when I was actually sending data to the socket, it was another socket. Also I changed the thread handling and made it with Task which seems to work a lot better with JavaFX scene.

groovy.lang.MissingPropertyException while Downloading Files from FTP Server

I want to create job in grails which download the files from ftp
server after certain interval of time say 2-3 days and store it on
specified local path. the same code with minor changes is written in
java which was working fine but when write the similar code in Grails
I'm facing the Error and not able to resolve it. Can any body Tell me
where I'm making mistake?
Following is the Error that I'm facing when job start.
JOB STARTED::************************************************************************************
2015-08-24 18:20:35,285 INFO org.quartz.core.JobRunShell:207 Job GRAILS_JOBS.com.hoteligence.connector.job.DownloadIpgGzipFilesJob threw a JobExecutionException:
org.quartz.JobExecutionException: groovy.lang.MissingPropertyException: No such property: ftpClient for class: com.hoteligence.connector.job.DownloadIpgGzipFilesJob [See nested exception: groovy.lang.MissingPropertyException: No such property: ftpClient for class: com.hoteligence.connector.job.DownloadIpgGzipFilesJob]
at grails.plugins.quartz.GrailsJobFactory$GrailsJob.execute(GrailsJobFactory.java:111)
at org.quartz.core.JobRunShell.run(JobRunShell.java:202)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573)
Caused by: groovy.lang.MissingPropertyException: No such property: ftpClient for class: com.hoteligence.connector.job.DownloadIpgGzipFilesJob
at com.hoteligence.connector.job.DownloadIpgGzipFilesJob.execute(DownloadIpgGzipFilesJob.groovy:93)
at grails.plugins.quartz.GrailsJobFactory$GrailsJob.execute(GrailsJobFactory.java:104)
... 2 more
/* I've added all the related dependencies in grails Build Config.
*/
package com.hoteligence.connector.job
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.codehaus.groovy.grails.commons.ConfigurationHolder as ConfigHolder;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
/**
* #author Gajanan
* this is back-end job which download Files from ftp server and store it on locally
*/
class DownloadIpgGzipFilesJob {
static triggers = {
simple repeatInterval: Long.parseLong(ConfigHolder.config.DEVICE_PING_ALERT_JOB_REPEAT_INTERVAL),
startDelay : 60000
}
def execute() {
try{
println "JOB STARTED::************************************************************************************";
/* following is the details which are required for server connectivity
*/
String server = ConfigHolder.config.IPG_SERVER_NAME;
int port = ConfigHolder.config.IPG_SERVER_PORT_NO;
String user = ConfigHolder.config.IPG_SERVER_USER_NAME;
String pass = ConfigHolder.config.IPG_SERVER_USER_PASSWORD;
String [] fileNames = ConfigHolder.config.IPG_DOWNLOADABLE_GZIP_FILE_LIST.split(",");
String downloadFilePath = ConfigHolder.config.IPG_GZIP_DOWNLOAD_LOCATION;
String fileDate = (todaysDate.getYear()+1900)+""+((todaysDate.getMonth()+1)<=9?("0"+(todaysDate.getMonth()+1)):(todaysDate.getMonth()+1))+""+todaysDate.getDate();
FTPClient ftpClient = new FTPClient();
/* Here we are making connection to the server and the reply
from server is printed on console
*/
ftpClient.connect(server, port);
showServerReply(ftpClient);
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("Connect failed");
return;
}
boolean success = ftpClient.login(user, pass);
showServerReply(ftpClient);
if (!success) {
System.out.println("Could not login to the server");
return;
}
/* Here we are iterate the FileList and download them to specified directory
*/
for(int i =0; i<fileNames.length;i++) {
String fileName = "on_"+ConfigHolder.config.IPG_DATA_COUNTRY_CODE+fileNames[i]+fileDate+".xml.gz";
System.out.println(fileName);
downloadFtpFileByName(ftpClient,fileName,downloadFilePath+fileName);
}
}
catch (IOException ex) {
System.out.println("Oops! Something wrong happened");
ex.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}
finally {
// logs out and disconnects from server
/* In finally block we forcefully close the connection and close the file node also
*/
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/* this function is nothing but to print the ftp server reply after connection to ftp server
*/
private static void showServerReply(FTPClient ftpClient) {
String[] replies = ftpClient.getReplyStrings();
if (replies != null && replies.length > 0) {
for (String aReply : replies) {
System.out.println("SERVER: " + aReply);
}
}
}
/* This is the actual logic where we copy the file from ftp
and store on local directory
this method accept three parameter FtpClient object, Name of the file which has to be downloaded from server and the path where downloaded file has to be stored
*/
private static void downloadFtpFileByName(FTPClient ftpClient,String fileName,String downloadfileName){
System.out.println("Strat Time::"+System.currentTimeMillis());
try {
String remoteFile1 = "/"+fileName; // file on server
File downloadFile1 = new File(downloadfileName); // new file which is going to be copied on local directory
OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));
Boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1);
if (success) {
System.out.println("File"+fileName+" has been downloaded successfully.");
}
else
{
System.out.println("File"+fileName+" has been DOWNLOAD FAILURE....");
}
outputStream1.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("END Time::"+System.currentTimeMillis());
}
}
Move this line:
FTPClient ftpClient = new FTPClient();
Outside of the try { ... } catch() block (ie, move it up to before the try)
You are declaring the local variable inside the try, then trying to use it in the finally block

How to Solve this (J2ME) : javax.microedition.io.ConnectionNotFoundException: error 0 in socket::open

i am trying to insert Data in my DataBase using this Code but i'am getting an exception :
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import com.sun.lwuit.*;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
public class MyMidlet extends MIDlet implements Runnable {
Form f;
TextField t1 ;
Label label1 ;
Button b1;
TextField tfNom ;
TextField tfPrenom ;
//Connexion
HttpConnection hc;
DataInputStream dis;
String url ;
StringBuffer sb ;
int ch;
public MyMidlet() {
Display.init(this);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
protected void startApp() throws MIDletStateChangeException {
f = new Form("Test");
tfNom = new TextField("nom : ");
tfPrenom = new TextField("prenom :");
b1=new Button("ok");
f.addComponent(tfNom); // append
f.addComponent(tfPrenom);
f.addComponent(b1);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("gooooo");
url= "http://localhost/J2ME/ajout.php";
sb = new StringBuffer();
//****************************
try {
hc = (HttpConnection) Connector.open(url+"?nom="+tfNom.getText()+"&prenom="+tfPrenom.getText());
dis = new DataInputStream(hc.openDataInputStream());
while ((ch = dis.read()) != -1) {
sb.append((char)ch);
}
// trim tna77i les espaces
if ("successfully added".equalsIgnoreCase(sb.toString().trim())) {
System.out.println("succes (added)");
}else{
System.out.println("Error While Adding Data");
}
} catch (IOException ex) {
ex.printStackTrace();
}
//***********************
System.out.println("I am Ouuuut");
}
});
f.show();
}
public void run() {
}
}
--> It does not work and I'am getting this exception :
i'am using NOKIA DevEnv for the first time. It used to work when I use it on Normal Netbeans J2ME.
Can any one help ?
gooooo
javax.microedition.io.ConnectionNotFoundException: error 0 in socket::open
- com.sun.midp.io.j2me.socket.Protocol.open0(), bci=0
- com.sun.midp.io.j2me.socket.Protocol.connect(), bci=143
- com.sun.midp.io.j2me.socket.Protocol.open(), bci=122
- com.sun.midp.io.j2me.socket.Protocol.openPrim(), bci=4
- com.sun.midp.io.j2me.http.Protocol.createConnection(), bci=13
- com.sun.midp.io.j2me.http.Protocol.connect(), bci=138
- com.sun.midp.io.j2me.http.Protocol.streamConnect(), bci=53
- com.sun.midp.io.j2me.http.Protocol.startRequest(), bci=7
- com.sun.midp.io.j2me.http.Protocol.sendRequest(), bci=33
- com.sun.midp.io.j2me.http.Protocol.sendRequest(), bci=3
- com.sun.midp.io.j2me.http.Protocol.openInputStream(), bci=6
- com.sun.midp.io.ConnectionBaseAdapter.openDataInputStream(), bci=5
- esprit.MyMidlet$1.actionPerformed(MyMidlet.java:89)
- com.sun.lwuit.util.EventDispatcher.fireActionSync(EventDispatcher.java:312)
- com.sun.lwuit.util.EventDispatcher.fireActionEvent(EventDispatcher.java:257)
- com.sun.lwuit.Button.fireActionEvent(Button.java:369)
- com.sun.lwuit.Button.released(Button.java:400)
- com.sun.lwuit.Button.pointerReleased(Button.java:476)
- com.sun.lwuit.Form.pointerReleased(Form.java:2059)
- com.sun.lwuit.Component.pointerReleased(Component.java:2065)
- com.sun.lwuit.Display.handleEvent(Display.java:1643)
- com.sun.lwuit.Display.edtLoopImpl(Display.java:894)
- com.sun.lwuit.Display.mainEDTLoop(Display.java:839)
- com.sun.lwuit.RunnableWrapper.run(RunnableWrapper.java:119)
- java.lang.Thread.run(), bci=5
I am Ouuuut
Either your application cannot connect to the internet or if it can, fails to connect to your web service using the link provided. Try entering the URL for your request in your web browser and see if it is reachable. If you are connecting to your web service through a specific port (eg. http://mylink.com:8085/my-web-service/), make sure that the specific port is not blocked.
Chris Mwai is right - the code provided tries to work with server at "http://localhost/J2ME/ajout.php" and obviously it doesn't exists. Probably the Netbeans project included server side code as well, which was deployed at localhost (user PC) and J2ME client connected to it from emulator.
You need to start server part somehow (it's specific to your project). In a real environment (not emulator) you will need to deploy the server part somewhere in internet and connect to it from app running on phone. So you will need to change url to that server. 'localhost' means a local server (your PC).

sending image from one mobile to another via sms using j2me language

i am programming a mobile application in j2me in which i need to send an image from one mobile to another via sms.
the problem is being encountered at the receiving end.the image is not being decoded properly.it is throwing ioexception....i m posting the code here..plz help me.
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import javax.wireless.messaging.*;
import java.io.IOException;
import javax.microedition.lcdui.game.*;
import java.lang.*;
import java.io.*;
public class receive_mms extends MIDlet implements CommandListener
{
Display disp;
//TextBox txtbox;
MessageConnection msgConn;
Message msg;
Form frm=null;
byte[] msgrev;
byte[] data;
//String msgrev;
Image im=null;
Image im1=null;
ImageItem img=null;
int i,j;
ByteArrayInputStream bais = null;
Command cmd_exit;
public receive_mms(){
disp=Display.getDisplay(this);
frm=new Form("photo dikho");
i=frm.getWidth();
j=frm.getHeight();
cmd_exit=new Command("exit",Command.EXIT,1);
frm.addCommand(cmd_exit);
frm.setCommandListener(this);
disp.setCurrent(frm);
Thread t1 = new Thread()
{
public void run()
{recieve();}
};
t1.start();
//txtbox=new TextBox("Recieve Text","",100,TextField.ANY);
}
public void commandAction(Command c,Displayable d)
{
if(c==cmd_exit)
{
notifyDestroyed();
}
}
public void startApp(){/*
disp.setCurrent(frm);
Thread t1 = new Thread()
{
public void run()
{recieve();}
};
t1.start();
*/
}
public void pauseApp(){}
public void destroyApp(boolean unconditional){}
public void recieve(){
//while(true)
//{
String mSenderAddress="";
try{
msgConn = (MessageConnection) Connector.open("sms://:1234");
System.out.println("11");
msg = msgConn.receive();// start listening and stuck here until a msg is received
System.out.println("12");
mSenderAddress = msg.getAddress();// Get info from message, from where da msg is beign sent
System.out.println("3");
System.out.println("add"+ mSenderAddress);
System.out.println("msg aya:" + msg);
msgConn.close();
}catch(Exception e){System.out.println(e);}
if (msg instanceof BinaryMessage) {
//try{
msgrev = ((BinaryMessage)msg).getPayloadData();
data=msgrev.toByteArray();
String val= new String(data);
System.out.println("yahoo");
System.out.println("yahoo1");
System.out.println(val);
create(data);
}
}
public void create(byte[] bs)
{
try
{
String str=bs.toString();
/*
StringBuffer d=new StringBuffer();
bais=new ByteArrayInputStream(bs);
DataInputStream ds=new DataInputStream(bais);
int len=bs.length;
System.out.println("len="+len);
if(len!=0)
{
int ch=0;
while((ch=ds.read())!=-1)
{
d.append((char)ch);
}
}
System.out.println(d);
str=d.toString();
*/
//str=bs.toString();
InputStream is= this.getClass().getResourceAsStream(str);
System.out.println("string is"+str);
im = (Image)Image.createImage(is);
System.out.println("line");
im1 = (Image)Image.createImage(im, 0, 0, i, j, Sprite.TRANS_NONE);
img = new ImageItem("yeh photo snd hui", im1, Item.LAYOUT_CENTER, "kyu nhi dikh rhi", Item.BUTTON);
frm.append(img);
}
catch (Exception e)
{
System.out.println(e);
}
}
}
You're doing a few very odd things:
converting the byte array to a String, particularly using byte[].toString()
attempting to get an InputStream by calling Class.getResourceAsStream() with a String that has been created from the byte array.
using SMS to send an Image
Class.getResourceAsStream() is intended to take a String identifying a resource file within the MIDlet's jar file.
The correct way to do this is to get the byte[] from the BinaryMessage and use this to create an Image using Image.createImage(bytes, 0, bytes.length);
Although, as you're sending it using SMS, I'd hope it was a very small image indeed or anybody using this app will incur high costs from splitting a large image over several SMSs. Beware also that some networks limit the number of parts that an SMS can be split into.
You would be much better off researching the MMS sending functionality provided by JSR 205.
You are getting wrong the data stream, here is how you must do it:
public void create(byte[] bs)
{
try
{
im = (Image)Image.createImage(bs, 0, bs.length);
im1 = (Image)Image.createImage(im, 0, 0, i, j, Sprite.TRANS_NONE);
img = new ImageItem("yeh photo snd hui", im1, Item.LAYOUT_CENTER, "kyu nhi dikh rhi", Item.BUTTON);
frm.append(img);
}
catch (Exception e)
{
System.out.println(e);
}
}
This should work.

Resources