Wednesday, September 16, 2009

Send text message from mobile device to computer-java mobile socket level Programming

In many projects we need to communicate mobile device and computers this code demonstrates how to communicate between them.here we have 2 codes one for mobile device and other for java server.server basically keep socket open and listen to that socket and mobile device get text from user and send them to server.this works perfectly with blackberry mobile device and if we can make few changes then able to work with any mobile device.use same host name and port number for both codes.server code add to netbeans project and run it.then mobile client project add to eclipse mobile project and run it.that's it

Server code

import java.net.*;
import java.io.IOException;
import java.io.*;
import java.util.Scanner;

public class Main {
    private static ServerSocket serverSocketin;
    private static ServerSocket serverSocketout;
    public static void main(String[] args)
    {
        try

        {
            serverSocketin = new ServerSocket(8206);
            serverSocketout = new ServerSocket(8207);
            DataSender dtsender = new DataSender();
            DataRiciver dataRiciver=new DataRiciver();
            dtsender.start();
            dataRiciver.start();
        }

         catch (IOException e)

        {
            e.printStackTrace();
        }
    }
    static class DataRiciver extends Thread
    {
        public void run(){
            while (true){
                try {
                    Socket incoming = serverSocketin.accept();
                    DataInputStream in = new DataInputStream(incoming.getInputStream());
                    String data="";
                    data = in.readLine();
                    System.out.println(data);
                    in.close();
                    incoming.close();
                     Thread.sleep(1000);
                }

                catch (Exception e)

                  {
                  }
        }

        }
    }

    static class DataSender extends Thread
    {
        public DataSender()
        {

        }

        public void run()
        {
            while (true)
            {
                try {
                    Scanner reader = new Scanner(System.in);
                    String data = reader.nextLine();
                    Socket outgoing = serverSocketout.accept();
                    PrintStream out = new PrintStream(outgoing.getOutputStream());
                    data=data+ "\n";
                    out.write(data.getBytes());
                    out.flush();
                    out.close();
                    outgoing.close();
                    Thread.sleep(1000);
                }
                catch (Exception ioe)
                {
                }
            }
        }
    }

}

 

Mobile client Code-BlackBerry

import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.MainScreen;
import javax.microedition.io.*;
import java.io.*;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
public class sss extends UiApplication
{
    public static void main(String[] args)
    {
        sss theApp = new sss();
        theApp.enterEventDispatcher();
    }
    public sss()
    {
        pushScreen(new UserInterfaceScreen());
    }
}

final class UserInterfaceScreen extends MainScreen
{
HorizontalFieldManager _fieldManagerTop;
VerticalFieldManager _fieldManagerMiddle;
HorizontalFieldManager _fieldManagerBottom;
BitmapField _bitmap;
Bitmap _canadaImage;
LabelField _label;
BasicEditField _input;
String _canadaCapital;
int displayed = 0;
    public UserInterfaceScreen()
    {
        super();
        LabelField title = new LabelField("Send Text To server",
        LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH);
        setTitle(title);
        _fieldManagerTop = new HorizontalFieldManager();
        _fieldManagerMiddle = new VerticalFieldManager();
        _fieldManagerBottom = new HorizontalFieldManager();
        add(_fieldManagerTop);
        add(new SeparatorField());
        add(_fieldManagerMiddle);
        add(new SeparatorField());
        add(_fieldManagerBottom);
        _canadaImage = Bitmap.getBitmapResource("canada.png");
        _bitmap = new BitmapField();
        _bitmap.setBitmap(_canadaImage);
        _fieldManagerTop.add(_bitmap);
        _canadaCapital = "txt";
        _label = new LabelField("Please press a button!");
        _input = new BasicEditField("Enter text here: ","ssss");
        _fieldManagerMiddle.add(_label);
        _fieldManagerMiddle.add(_input);
FieldChangeListener listenerCanada = new FieldChangeListener()
        {
            public void fieldChanged(Field field, int context)
            {
                _bitmap.setBitmap(_canadaImage);
                _input.setText(_canadaCapital);
                displayed = 0;
            }
        };
//add button
ButtonField canadaButton = new ButtonField("send");
canadaButton.setChangeListener(listenerCanada);
_fieldManagerBottom.add(canadaButton);

};
protected void makeMenu(Menu menu, int instance) {
menu.add(_changeCapital);
menu.add(_close);
}

private MenuItem _changeCapital = new MenuItem("Send to Server", 110,10)
{
public void run()
{
//=====================================================
//This code block do client task this part can use with any mobile device
//with few changes
try {
    StreamConnection conn;
    conn = (StreamConnection)Connector.open("socket://localhost:8206;deviceside=true");
    //open and connect to server socket use your host name and socket here
    PrintStream output = new PrintStream(conn.openOutputStream());
    String data=_input.getText();;
    //get input text from the user
    output.write(data.getBytes());
    //write to out put
    output.flush();
    output.close();
    conn.close();
    }
catch (Exception e)
    {
    }
//===================================================
}
};

private MenuItem _close = new MenuItem("Close", 110, 10)
{
    public void run()
    {
        onClose();
    }
};

public boolean onClose()
{
    Dialog.alert("Goodbye!");
    System.exit(0);
    return true;
}

}

Mobile Code –java Mobile

package client;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;

public class MobileClient extends MIDlet implements CommandListener {
    private Display display;
    private Command exit;
    private Command send;
    //private Command back;
    private TextBox textBox;

    ServerListner serverListner = new ServerListner();

    public MobileClient() {

        display = Display.getDisplay(this);
        send=new Command("Send",Command.SCREEN,1);
        exit = new Command("Exit", Command.EXIT, 2);

        textBox = new TextBox("Recived massage", "no massage", 81, 0);
        textBox.addCommand(send);
        textBox.addCommand(exit);
        textBox.setCommandListener(this);

        //output=new PrintStream(connection.openOutputStream());

    }

    protected void startApp() throws MIDletStateChangeException {
        display.setCurrent(textBox);
        serverListner.start();

    }

    protected void pauseApp() {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    protected void destroyApp(boolean b) throws MIDletStateChangeException {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public void commandAction(Command command, Displayable displayable) {
        if (command == exit) {
            try {
                destroyApp(false);
                notifyDestroyed();
            } catch (MIDletStateChangeException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
        else if(command ==send)
        {
            String data=textBox.getString();
            sendData(data);
        }
    }

    public void sendData(String data) {
        try {
            StreamConnection connection = (StreamConnection) Connector.open("socket://localhost:8206");
            PrintStream output = new PrintStream(connection.openOutputStream());
            data=data +"\n";
            output.write(data.getBytes());
            output.flush();
            output.close();
            connection.close();

        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    class ServerListner extends Thread {

        public void run() {
            try {
                while (true) {
                    StreamConnection connection = (StreamConnection) Connector.open("socket://localhost:8206");
                    InputStream in = connection.openInputStream();
                    StringBuffer buffer = new StringBuffer();
                    int ch;
                    while ((ch = in.read()) != -1) {
                        if (ch != '\n') {
                            buffer.append((char)ch);
                        } else {

                        }
                    }
                    textBox.setString(buffer.toString());
                    display.setCurrent(textBox);

                    // connection.close();
                    in.close();
                    connection.close();
                     Thread.sleep(1000);
                }
            } catch (Exception ie) {
                ie.printStackTrace();
            }
        }
    }
}

1 comment: