Search code examples
socketsjava-mewifimidp

j2me-j2se socket connection


I am working on a j2me application that sends data to PC over WiFi using Sockets. What should be the server address? i.e. What should I use instead of 'localhost' in the code below?

Client Code(j2me):

SocketConnection sc = (SocketConnection)
Connector.open("socket://localhost:9002");
DataOutputStream os = null;
try{
    os = sc.openDataOutputStream();
    os.writeUTF("Test Dama");
} finally{
  sc.close();
  os.close();
}

Server Code(j2se):

    ServerSocket echoServer = null;
    String line;
    DataInputStream is;

    Socket clientSocket = null;

    try {
       echoServer = new ServerSocket(9002);
    }
    catch (IOException e) {
       System.out.println(e);
    }
    try {
       clientSocket = echoServer.accept();
       is = new DataInputStream(clientSocket.getInputStream());

       line = is.readUTF();

       System.out.println("Received:"+line);

    }
    catch (IOException e) {
       System.out.println(e);
    }

Solution

  • That depends on the ip/domain of the server.

    If you are running things on a local network (in your home/office) then just find out what is the ip of the machine running the server code. In linux systems you can find that with the command ifconfig, then in the output the ip address is under inet addr. In windows systems use ipconfig /all.

    Once you have the ip of the machine running the server, just put that instead of the localhost that you are using in the client.

    If you want this to work on the public network though, you'll have to run the server code on a machine that has a static ip (or use dynamic DNS).