J2ME socket programming

i am doing a final year project in which i have a java program running on pc connected to internet which uses bsnl as an isp.i am provided with a public ip
i have a J2me client.I connect the mobile to internet with gprs.
I use gprs wap settings of vodafone which uses proxies.i have searched internet
and found out that i dont access actual internet using gprs wap. ie we only access wap sites.i want to try purely socket communications.i am using n72 mobile for midlets and socket communications.
sc = (SocketConnection)Connector.open("socket://my bsnl ip:5000");
is = sc.openInputStream();
os = sc.openOutputStream();
i have used simulator and tried communication it was successful.
i tried socket communications form internet client and my server
i also tried different ports too.
now with actual n72 mobile i am having a problem of socket communication.
summary of problems
1.Is direct socket communication possible through gprs with client on N72
with a java server
2.Do i have to use wap settings or internet settings of vodafone

here is my client on mobile..it is same as networkdemo in suns WTK2.5
we used it for testing the connection...
SocketMIdlet:
package socket;
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class SocketMIDlet extends MIDlet implements CommandListener {
private static final String SERVER = "Server";
private static final String CLIENT = "Client";
private static final String[] names = { SERVER, CLIENT };
private static Display display;
private Form f;
private ChoiceGroup cg;
private boolean isPaused;
private Server server;
private Client client;
private Command exitCommand = new Command("Exit", Command.EXIT, 1);
private Command startCommand = new Command("Start", Command.ITEM, 1);
public SocketMIDlet() {
display = Display.getDisplay(this);
f = new Form("Socket Demo");
cg = new ChoiceGroup("Please select peer", Choice.EXCLUSIVE, names, null);
f.append(cg);
f.addCommand(exitCommand);
f.addCommand(startCommand);
f.setCommandListener(this);
display.setCurrent(f);
public boolean isPaused() {
return isPaused;
public void startApp() {
isPaused = false;
public void pauseApp() {
isPaused = true;
public void destroyApp(boolean unconditional) {
if (server != null) {
server.stop();
if (client != null) {
client.stop();
public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
} else if (c == startCommand) {
String name = cg.getString(cg.getSelectedIndex());
if (name.equals(SERVER)) {
server = new Server(this);
server.start();
} else {
client = new Client(this);
client.start();
Client:
package socket;
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class Client implements Runnable, CommandListener {
private SocketMIDlet parent;
private Display display;
private Form f;
private StringItem si;
private TextField tf;
private boolean stop;
private Command sendCommand = new Command("Send", Command.ITEM, 1);
private Command exitCommand = new Command("Exit", Command.EXIT, 1);
InputStream is;
OutputStream os;
SocketConnection sc;
Sender sender;
public Client(SocketMIDlet m) {
parent = m;
display = Display.getDisplay(parent);
f = new Form("Socket Client");
si = new StringItem("Status:", " ");
tf = new TextField("Send:", "", 30, TextField.ANY);
f.append(si);
f.append(tf);
f.addCommand(exitCommand);
f.addCommand(sendCommand);
f.setCommandListener(this);
display.setCurrent(f);
* Start the client thread
public void start() {
Thread t = new Thread(this);
t.start();
public void run() {
try {
sc = (SocketConnection)Connector.open("socket://59.95.23.211:4000");
si.setText("Connected to server");
is = sc.openInputStream();
os = sc.openOutputStream();
// Start the thread for sending messages - see Sender's main
// comment for explanation
sender = new Sender(os);
// Loop forever, receiving data
while (true) {
StringBuffer sb = new StringBuffer();
int c = 0;
while (((c = is.read()) != '\n') && (c != -1)) {
sb.append((char)c);
if (c == -1) {
break;
// Display message to user
si.setText("Message received - " + sb.toString());
stop();
si.setText("Connection closed");
f.removeCommand(sendCommand);
} catch (ConnectionNotFoundException cnfe) {
Alert a = new Alert("Client", "Please run Server MIDlet first", null, AlertType.ERROR);
a.setTimeout(Alert.FOREVER);
a.setCommandListener(this);
display.setCurrent(a);
} catch (IOException ioe) {
if (!stop) {
ioe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
public void commandAction(Command c, Displayable s) {
if ((c == sendCommand) && !parent.isPaused()) {
sender.send(tf.getString());
if ((c == Alert.DISMISS_COMMAND) || (c == exitCommand)) {
parent.notifyDestroyed();
parent.destroyApp(true);
* Close all open streams
public void stop() {
try {
stop = true;
if (sender != null) {
sender.stop();
if (is != null) {
is.close();
if (os != null) {
os.close();
if (sc != null) {
sc.close();
} catch (IOException ioe) {
Sender:
package socket;
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class Sender extends Thread {
private OutputStream os;
private String message;
public Sender(OutputStream os) {
this.os = os;
start();
public synchronized void send(String msg) {
message = msg;
notify();
public synchronized void run() {
while (true) {
// If no client to deal, wait until one connects
if (message == null) {
try {
wait();
} catch (InterruptedException e) {
if (message == null) {
break;
try {
os.write(message.getBytes());
os.write("\r\n".getBytes());
} catch (IOException ioe) {
ioe.printStackTrace();
// Completed client handling, return handler to pool and
// mark for wait
message = null;
public synchronized void stop() {
message = null;
notify();
Server:
package socket;
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class Server implements Runnable, CommandListener {
private SocketMIDlet parent;
private Display display;
private Form f;
private StringItem si;
private TextField tf;
private boolean stop;
private Command sendCommand = new Command("Send", Command.ITEM, 1);
private Command exitCommand = new Command("Exit", Command.EXIT, 1);
InputStream is;
OutputStream os;
SocketConnection sc;
ServerSocketConnection scn;
Sender sender;
public Server(SocketMIDlet m) {
parent = m;
display = Display.getDisplay(parent);
f = new Form("Socket Server");
si = new StringItem("Status:", " ");
tf = new TextField("Send:", "", 30, TextField.ANY);
f.append(si);
f.append(tf);
f.addCommand(exitCommand);
f.setCommandListener(this);
display.setCurrent(f);
public void start() {
Thread t = new Thread(this);
t.start();
public void run() {
try {
si.setText("Waiting for connection");
scn = (ServerSocketConnection)Connector.open("socket://:4000");
// Wait for a connection.
sc = (SocketConnection)scn.acceptAndOpen();
si.setText("Connection accepted");
is = sc.openInputStream();
os = sc.openOutputStream();
sender = new Sender(os);
// Allow sending of messages only after Sender is created
f.addCommand(sendCommand);
while (true) {
StringBuffer sb = new StringBuffer();
int c = 0;
while (((c = is.read()) != '\n') && (c != -1)) {
sb.append((char)c);
if (c == -1) {
break;
si.setText("Message received - " + sb.toString());
stop();
si.setText("Connection is closed");
f.removeCommand(sendCommand);
} catch (IOException ioe) {
if (ioe.getMessage().equals("ServerSocket Open")) {
Alert a = new Alert("Server", "Port 5000 is already taken.", null, AlertType.ERROR);
a.setTimeout(Alert.FOREVER);
a.setCommandListener(this);
display.setCurrent(a);
} else {
if (!stop) {
ioe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
public void commandAction(Command c, Displayable s) {
if ((c == sendCommand) && !parent.isPaused()) {
sender.send(tf.getString());
if ((c == Alert.DISMISS_COMMAND) || (c == exitCommand)) {
parent.notifyDestroyed();
parent.destroyApp(true);
* Close all open streams
public void stop() {
try {
stop = true;
if (is != null) {
is.close();
if (os != null) {
os.close();
if (sc != null) {
sc.close();
if (scn != null) {
scn.close();
} catch (IOException ioe) {
Client connects to server...server can send messages to server..but clients
message does not reach server..that it cant be observed on server..how to debug jar file on mobile??

Similar Messages

  • Socket Programing in J2ME - Confused with Sun Sample Code

    Hai Everybody,
    I have confused with sample code provided by Sun Inc , for the demo of socket programming in J2ME. I found the code in the API specification of J2ME. The code look like :-
    // Create the server listening socket for port 1234
    ServerSocketConnection scn =(ServerSocketConnection) Connector.open("socket://:1234");
    where Connector.open() method return an interface Connection which is the base interface of ServerSocketConnection. I have confused with this line , is it is possible to cast base class object to the derived class object?
    Plese help me in this regards
    Thanks in advance
    Sulfikkar

    There is nothing to be confused about. The Connector factory creates an implementation of one of the extentions of the Connection interface and returns it.
    For a serversocket "socket://<port>" it will return an implementation of the ServerSocketConnection interface. You don't need to know what the implementation looks like. You'll only need to cast the Connection to a ServerSocketConnection .

  • TCP/IP socket programming in ABAP

    Hi,
    Is there any method of TCP socket programming in ABAP? For example is there any function module for creating a socket for a IP address and port number. After that, is it possible to send binary/text data to a connected IP/port destination. I need such a solution because I need to send raw data (native commans) to barcode printer on our network which has a static IP address and listens incoming data through a fixed port number specified in its documentation. For a solution, I coded some .NET VB and built a small application that acts as a RFC server program which can be called by SAP according to definitions I made in SM59 (I defined a new TCP connection and it works well sometimes!). In this application, data coming from SAP are transferred to the barcode printer. This is achived by the .NET Socket class library. This solution works well but after a few subsequent call from SAP, connection hangs! SAP cannot call the application anymore, I test the connection in SM59 and it also hangs, so I need to restart the VB application, but this is unacceptable in our project.
    As a result, I decided to code the program that will send data to the printer in ABAP as a function module or subroutine pool, so is there any way to create a socket in ABAP and connect to specific IP/port destination? I searched for possible function modules in SE37 and possible classes in SE24 but unfortunately I could not find one. For example, do know any kind of system function in ABAP (native commands executed by CALL statement), that can be used for this purpose?
    I would appreciate any help,
    Kind regards,
    Tolga
    Edited by: Tolga Togan Duz on Dec 17, 2007 11:49 PM

    Hi,
    I doubt that there is a low level API for sockets in ABAP. There is API for HTTP but probably that won't help you. As a workaround you can use external OS commands (transactions SM69 and SM49). For example on Unix you can use netcat to transfer file. Your FM needs to dump data into folder and then call netcat to transfer file.
    Cheers

  • File descriptor leak in socket programming

    We have a complex socket programming client package in java using java.nio (Selectors, Selectable channel).
    We use the package to connect to a server.
    Whenever the server is down, it tries to reconnect to the server again at regular intervals.
    In that case, the number of open file descriptors build up with each try. I am able to cofirm this using "pfile <pid>" command.
    But, it looks like we are closing the channels, selectors and the sockets properly when it fails to connect to the server.
    So we are unable to find the coding that causes the issue.
    We run this program in solaris.
    Is there a tool to track down the code that leaks the file descriptor.
    Thanks.

    Don't close the selector. There is a selector leak. Just close the socket channel. As this is a client you should then also call selector.selctNow() to have the close take final effect. Otherwise there is also a socket leak.

  • Java Swing and Socket Programming

    I am making a Messenger like yahoo Messenger using Swing and Socket Programming ,Multithreading .
    Is this techology feasible or i should try something else.
    I want to display my messenger icon on task bar as it comes when i install and run Yahoo Messenger.
    Which class i should use.

    I don't really have an answer to what you are asking. But I am developing the same kind of application. I am using RMI for client-server and server-server (i have distributed servers) communication and TCP/IP for client-client. So may be we might be able to help each other out. My email id is [email protected]
    Are you opening a new socket for every conversation? I was wondering how to multithread a socket to reuse it for different connections, if it is possible at all.
    --Poonam.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Network and socket programming in python

    i want to learn network and socket programming but i would like to do this in python.Reason behind this is that python is very simple and the only language i know . 
    anybody can suggest me which book should i pick.
    the book should have following specification--
    1)not tedious to follow
    2)lots of example
    3)starts with some networking stuff and then get into codes
    thanks in advance with regards.

    hmm. well, your requirements are almost contradictory.
    Not sure about books, except maybe dusty's.
    Most python books cover at least some network programming (unless the book is topic specific).
    I use lots of python-twisted at work. I mean ALOT. I wouldn't recommend it to someone looking for non-tedious though! I also like gevent/eventlet (esp. the async socket wrappers).
    EDIT: Wow. My post wasn't really helpful at all. Sorry!
    Last edited by cactus (2010-09-04 09:16:54)

  • Socket programming usin nio package

    hello frens i m new to socket programming
    i come to know that nio packaage provides more sophisticated and efficient API to deal with socket programming issue
    I need to know where i can get tutorial about socket programming using nio pacakage

    Try google
    http://www.google.co.uk/search?q=java+nio+tutorial

  • Daemon and socket programming

    Hi,
    I have been given a new project whereby I have to:
    1) Write a class with a method that takes as an argument an xml document, communicate s with a SOAP server and return the SOAPs response (in this case a ResponseWrapper object).
    2) This then has to be implemented as a Daemon, that listens to a particular socket.
    The reason for this being is that it can be uploaded to a server, allowing a pearl program to send the XML to the Daemon, have this contact the SOAP server and then return the SOAPs response back to the pearl program.
    I am aware that this sounds unnecessarily complicated but it does have to be implemented this way.
    I have written the class and it successfully communicates with the SOAP server and returns a response, but have no idea how to implement it as a Daemon and have had no experience with socket programming.
    Could anyone point me to a tutorial or give me some pointers in how to get started?
    Thanks,

    It was an option to use a Web Service, but I was told
    that due to security issues it would take to long to
    write all the necessary checks and interceptors
    (which I know how to do), so I should implement it
    this way (which I don't know how to do); since it is
    sitting behind the firewall it would not be
    accessible for spoofing.Huh? You realize that tons of very sensitive information is transmitted all over the internet using Web Services right?
    I have had no experience
    with implementing this type of thing before, What is your level of experience then? This may be over your head. I'm not saying that sockets and daemons are advanced concepts, but I wouldn't throw a beginner into that task.

  • [Urgent]3G Socket programming

    May I use socket for 3G networks?
    I use the demo provided by the WTK2.5-Beta(NetworkDemo), it works well in the simulator. However, when I download the program to the mobile phone, it seems that the mobile phone that runs ServerSocket cannot create the socket ... all the 2 handsets use a 3G SIM card provided by a Hong Kong ISP smartTone ... What can I do?
    Please help~ provide any web page of codes, thanks very much!

    1.     We want to create a socket connection which can
    remain open and live for ever till it is closed. Is
    this possible in java socket programming?Yes, but it isn't practical in the real networking world. So your code had better be prepared to deal with network failures.
    2.     I am just wondering in order to communicate with
    the third party over the socket connection, does this
    other party requires to run something specific on
    their end? I am not able to understand how will my
    java code communicate with their server otherwise.It has nothing to do with java. Sockets send and recieve messages. The applications at either end, regardless of the language that they are written in, must handle those messages.
    3.     Can we send and receive data over the socket
    created and also is their specific format for the
    data? Yes.
    Can we send files of data over this connection?Yes. (Although I don't know why you would need to do that if you are doing credit card auths.)
    It would be great if someone can comment on these
    questions and also if possible please provide some
    code that can create socket connection.The tutorial.....
    http://java.sun.com/docs/books/tutorial/networking/sockets/index.html

  • Can i run UDP  client and UDP  server socket program in the same pc ?

    hi all.
    when i execute my UDP client socket program and UDP server socket program in the same pc ,
    It's will shown the error msg :
    "Address already in use: Cannot bind"
    but if i run UDP client socket program in the remote pc and UDP server socket program run in local pc , it's will success.
    anybody know what's going on ?
    any help will be appreciated !

    bobby92 wrote:
    i have use a specified port for UDP server side , and for client define the server port "DatagramSocket clientSocket= new DatagramSocket(Server_PORT);"Why? The port you provide here is not the target port. It's the local port you listen on. That's only necessary when you want other hosts to connect to you (i.e. when you're acting as a server).
    The server should be using that constructor, the client should not be specifying a port.
    so when i start the udp server code to listen in local pc , then when i start UDP client code in local pc ,i will get the error "Address already in use: Cannot bind"Because your client tries to bind to the same port that the server already bound to.

  • RESTFUL Web Services vs Socket Programming Performance

    Hi guys,
    I will have an application which will have a service serving about to 30 million users/day and a mean of 5 requests/user.
    It means that there will be about 150 million requests per day. I will have two servers behind a load balancer and my clients will be both Java and C++.
    I think to implement RESTFUL Web Services but afraid of performance issues.
    Did you have a knowledge about the performances of web service and socket programming in such a high loaded project?
    Tnx.
    Ayberk

    ayberkcansever wrote:
    Hi guys,
    I will have an application which will have a service serving about to 30 million users/day and a mean of 5 requests/user.
    It means that there will be about 150 million requests per day. I will have two servers behind a load balancer and my clients will be both Java and C++.
    I think to implement RESTFUL Web Services but afraid of performance issues.
    Did you have a knowledge about the performances of web service and socket programming in such a high loaded project?It depends on the CPUs, RAM, disks, and network configurations of those servers.
    It depends on how the requests are distributed throughout the day.
    It depends on how big the requests are and how big the responses are.

  • HELP : Convert socket programming from Ipv4 to IPv6

    Hi all,
    I need help in converting my Ipv4 socket programing to Ipv6. How can I do this? I already have an Ipv4 socket programming that is working but when I tried to convert it to Ipv6 it doesn't work .
    this is my Ipv4 socket programming :
    DatagramPacket sendPacket;
    DatagramSocket sock;
    ip = jtfDIP.getText().trim();
    try{
    sock = new DatagramSocket();
    add = InetAddress.getByName(ip);
    sendPacket = new DatagramPacket(buf,buf.length,add,port);
    Please help me. How can I convert this to Ipv6. Thank you.

    Socket sock = new Socket("host");
    or
    Socket sock = new Socket("192.168.1.1");
    or
    Socket sock = new Socket("www.host.com");
    or
    Socket sock = new Socket("hhhh.hhhh.hhhh.hhhh");
    Get it? Just use whatever host, domain name, or IP you need, the underlying native code does the work - you'll never need to do anything, for the most part.

  • J2ME game programming

    Helo everyone,
    I am working in j2me game programming plz if
    any one know how make image as small as possible
    in our game program.?
    I am using *.png format of image which is working well
    in game but my game size is very big so plz help me to get
    out of this problem
    Thank u
    Aman Gautam

    hi,
    if you want to do any kind of game programming in J2ME, i suppose you would require to use the Canvas class, well there are a few good resources.. try out
    www.billday.com
    www.javamobiles.com..
    that ought to get u started.
    cheerz
    ynkrish

  • J2Me game programming plz help

    Helo everyone,
    I am working in j2me game programming plz if
    any one know how make image as small as possible
    in our game program.?
    I am using *.png format of image which is working well
    in game but my game size is very big so plz help me to get
    out of this problem
    Thank u
    Aman Gautam

    I solved the same problem by using indexed color images instead of true color.
    So, for example, if you have a colorful background you can convert it to a 256 color image.
    Depending on your specific image and the devices you'll see it on you may or may not notice the difference, but the file size is generally smaller.
    Then you can push further for smaller elements, like, say, a moving object like a pointer or a starship, you can reduce it to 60 or 30 colors, or even less.
    Another technique is to use tiles to build up the background instead of big images. With MIDP2.0 there's the TiledLayer, but you can implement the same with some code also on MIDP1.0 if backward compatibility is of concern.

  • How to control tcp connection with java tcp socket programing ??

    Hi,
    I am connecting a server as using java socket programming.
    When server close the connection (socket object) as using close() method ,
    I can not detect this and My program continue sending data as if there is a connection with server.
    How to catch the closing connection ( socket ) with java socket programming.
    My Client program is as following :
    import java.io.PrintWriter;
    import java.net.Socket;
    public class client
      public client()
       * @param args
      public static void main(String[] args)
        Socket socket=null;
        PrintWriter pw=null;
        try
                          socket = new Socket("localhost",5555);
                          pw = new PrintWriter(socket.getOutputStream(),true);
                          int i=0;
                          while (true)
                            i++;
                            pw.println(i+". message is being send.");
                            Thread.sleep(5000);
        } catch (Exception ex)
                          ex.printStackTrace();
        } finally
                          try
                            if(pw!=null)pw.close();
                            if(socket!=null)socket.close();
                          } catch (Exception ex)
                            ex.printStackTrace();
                          } finally
    }

    I changed the code as following. But I couldn't catch the EOFException when I read from the socket. How can I catch this exception ?
    import java.io.BufferedReader;
    import java.io.EOFException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.Socket;
    import java.net.UnknownHostException;
    public class client
      public client()
       * @param args
      public static void main(String[] args)
        Socket socket=null;
        PrintWriter pw=null;
        BufferedReader bufIn=null;
        InputStreamReader inRead=null;
        InputStream in=null;
        try
                          socket = new Socket("localhost",5555);
                          in = socket.getInputStream();
                          inRead = new InputStreamReader(in);
                          bufIn = new BufferedReader(inRead);
                          pw = new PrintWriter(socket.getOutputStream(),true);
                          int i=0;
                          while (true)
                            i++;
                            try
                              bufIn.readLine();
                              pw.println(i+". message is being send.");
                              System.out.println(i+". message has been send");
                            } catch (Exception ex2)
                              System.out.println(ex2.toString());
                              System.out.println(i+". message could not be send");
                            } finally
                            Thread.sleep(5000);
        } catch (EOFException ex)
                          ex.printStackTrace();
        } catch (InterruptedException ex)
                          ex.printStackTrace();
        } catch (IOException ex)
                          ex.printStackTrace();
        } finally
                          try
                            if(pw!=null)pw.close();
                            if(socket!=null)socket.close();
                          } catch (Exception ex)
                            ex.printStackTrace();
                          } finally
    }

Maybe you are looking for

  • DVD drive turned on randomly with no disk

    At least I think that is what it was. I had no disk in the drive, and all of a sudden I heard a loud spinning sound which at first I thought wa sa fan going nuts. But then realized it sounded like the DVD drive. *It stopped after like ten seconds and

  • "You've been signed out" CC Message

    My CC Desktop Application manager became signed out last night, and responded with the 'You've been signed out' message every time I tried to log back on.  So I had a Google and found the 'Delete opm.db' tip.  I tried to be caucious and just add a .b

  • Feasibility of Dashboard

    Hi, We have requiremeny where we have to display detals of cost datawarehouse. We want to check whether dashboard will be the best tool to be used for our requirements. Requirements: 1) Showing data (table) on basis of Country, state, city hierarchy

  • Convert SQL statements to JAVA Code ?

    Using SQL queries Can I convert SQL statements to JAVA Code ? Edited by: user11238895 on Jun 7, 2009 10:54 PM Edited by: user11238895 on Jun 7, 2009 11:12 PM

  • Problem with external libraries and Web DynPro

    Hello, we're stuck here. We're trying for a week now to include external libraries(e.g. Hibernate) into our Web DynPro Project, without success so far. We read every single forum and blog entry we could find on this topic. E.g.: /people/valery.silaev