socket connection works well in wireless toolkit but no in my nokia phone - sockets

wireless toolkit code
//j2me code for client mobile
public class TCPConnectSend extends MIDlet implements CommandListener {
Display display;
public TCPConnectSend0 () {
frm = new Form ("TCPConnectSend0");
sendCmd = new Command("Send",Command.SCREEN, 1);
frm.addCommand(sendCmd);
frm.setCommandListener(this);
text = new TextField("text:","",40,TextField.ANY);
frm.append(text);
}
public void startApp() {
if(display==null) {
display = Display.getDisplay (this);
}
display.setCurrent(frm);
try {
conn=(SocketConnection)Connector.open("socket://|ip-address|:80");//socket connection to the server
outs=conn.openOutputStream();
} catch(IOException e) { }
}
public void pauseApp() { }
public void destroyApp(boolean unconditional) { }
public void commandAction(Command c, Displayable s) {
if(c==sendCmd) {
try {
outs.write((text.getString()+"\n").getBytes());
} catch(IOException e) {}
} else { }
}
}
server code
//this receives the socket request from client
class TCPServer
{
public static void main(String argv[]) throws Exception
{
try {
ServerSocket server = new ServerSocket(80);
System.out.println("ip address : "+InetAddress.getLocalHost());
System.out.println("waiting for connection");
Socket s1 = server.accept();
System.out.println("connection established");
BufferedReader br = new BufferedReader(new
InputStreamReader(s1.getInputStream()));
while (true) {
String str1 = br.readLine();
System.out.println("client says :" +str1);
if (str1.equals("quit"))
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
//after running this code i m getting a java security exception in my nokia phone any other port no is no responding in the nokia phone

the problem happened because Nokia was blocking the 80 port no for some of its system application so changing of port no along with public ip address did the trick

You should add the public IP of the server in your client code ex.
(SocketConnection)Connection.open( "socket://105.225.251.58" + ":" + "port" );

Note that to use privileged ports like 80, 443, 8080 and generally anything below 1000, you need a code signing certificate(e.g from Thawte) for a real phone.
Otherwise, still to higher un-privileged ports likes 8000 etc

Related

javax.microedition.io.ConnectionNotFoundException: error 10061 in socket::open

javax.microedition.io.ConnectionNotFoundException: error 10061 in socket::open
I have this error with j2me - in execution.
I tried searching, but it didn't help.
Code:
Connector.open("socket://127.0.0.1:7777")
According to ConnectionNotFoundException documentation "This class is used to signal that a connection target cannot be found, or the protocol type is not supported".
socket is a supported protocol, so the connection target cannot be found. Be sure that 127.0.0.1:7777 is up, running and that is does support receiving a Socket connection.
You may try below Java code:
public class Server {
static boolean done = false;
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(7777);
while (!done) {
final Socket socket = server.accept();
new Thread() {
public void run() {
treatSocket(socket);
}
}.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
static void treatSocket(Socket socket) {
// treat socket data
}
}

Java 7 doesn't throw BindException when binding an already used port using ServerSocket

I'm experimenting on ServerSocket in Java on Windows 7 x64.
I wrote a little program that host a HTTP server on port 8080 and only returns a static HTML response that contains the toString() of the class loader.
What I did in the program mainly:
Create a ServerSocket
call setReuseAddress(false) on the serverSocket
Bind port 8080 to this socket
Use a forever loop to accept socket and give response
First I tried with JRE 1.6.0_23 and everything is great: first instance launched and responds normally, second instance cannot be launched since exception is thrown:
Exception in thread "main" java.net.BindException: Address already in use: JVM_Bind
Unexpected thing happens when I tried with JRE 1.7.0_5: both instance can be launched successfully but only the first instance gives responses. After the first instance is kill, the second instance then starts to responds.
Am I doing anything wrong or is this a bug of JRE 7?
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class TestServerSocket {
private static final String HEADER = "HTTP/1.1 200 OK\r\n" + "Content-type: text/html\r\n"
+ "Connection: close\r\n" + "\r\n";
private static final int PORT = 8080;
private static void handle(Socket socket) {
System.out.println(socket.getInetAddress() + ":" + socket.getPort());
StringBuilder buffer = new StringBuilder();
buffer.append(HEADER);
buffer.append(TestServerSocket.class.getClassLoader());
try {
socket.getOutputStream().write(buffer.toString().getBytes());
} catch (IOException e) {
} finally {
try {
socket.close();
} catch (IOException e) {
}
}
}
public static void main(String[] args) throws IOException {
int port;
try {
port = Integer.parseInt(args[0]);
} catch (Exception e) {
port = PORT;
}
final ServerSocket server = new ServerSocket();
server.setReuseAddress(false);
server.bind(new InetSocketAddress(port));
// Terminator thread, stop when Ctrl-D is entered
new Thread() {
public void run() {
try {
while (System.in.read() != 4);
} catch (IOException e) {
e.printStackTrace();
}
try {
server.close();
} catch (IOException e) {
}
System.exit(0);
}
}.start();
System.out.println("Listening on: " + port);
Socket client = null;
while (true) {
try {
client = server.accept();
handle(client);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
To Isolate the problem, I would recommend that you run the following test code.
Apache HttpCore basic server. It's standard API and uses ServerSocket in this particular example, so there is a very small chance that it would fail on your environment ( java 7).
In case it fails you will know for sure problem is not with your code. Meanwhile I will try your code on JDK 7 on my work-machine and will update.

How work with socket and hostnames in Java?

Recently I had to change my router, it was an Belking for one D-Link, my program worked it with my Belkin router but not now with the D-Link router.
Here is my program:
The client:
package brainset.socket;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
/**
*
* #author Valter
*/
public class Client {
public static void main(String[] args) {
Socket s = null;
PrintStream ps = null;
try{
s = new Socket("valterhenrique.dyndns.info", 40000);
ps = new PrintStream(s.getOutputStream());
ps.println("lamp");
}catch(IOException e){
System.out.println("Some problem happens.");
e.printStackTrace();
}finally{
try{
s.close();
}catch(IOException e){}
}
}
}
And here's my server:
package brainset.socket;
// imports
public class Server {
private Supervisory supervisory;
public Server(Supervisory supervisory) {
this.supervisory = supervisory;
}
public void start() {
ThreadServer ts = new ThreadServer();
Thread t = new Thread(ts);
t.start();
}
class ThreadServer extends Thread {
public void run() {
ServerSocket ss = null;
Socket socket = null;
BufferedReader br = null;
try {
ss = new ServerSocket(40000);
socket = ss.accept();
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message;
while ((message = br.readLine()) != null) {
System.out.println("message:" + message);
try {
if (message.equals("lamp")) {
supervisory.active();
supervisory.switchLamp();
} else if (message.contains("airConditioning")) {
String airConditioning[] = message.split(":");
// temperature[0] = 'temperature'
// temperature[1] = temperature value
supervisory.active();
supervisory.changeTemperature(Float.parseFloat(airConditioning[1]));
}
} catch (Exception ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
socket = ss.accept();
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
socket.close();
ss.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
public static void main (String args[]){
Server s = new Server(new Supervisory("192.168.1.149", "192.168.1.255", 101));
s.start();
}
}
I already opened a port in my new router and update the hostname in DynDns.org but still keeping launching an exception:
java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at java.net.Socket.<init>(Socket.java:375)
at java.net.Socket.<init>(Socket.java:189)
at brainset.socket.Client.main(Client.java:28)
If I change the hostname 'valterhenrique.dyndns.info' it works, but this is not what I want, I want to works with the hostname because I'm in a dynamic ip network.
Any idea ?
I think you need permit external access to your network. In the Port Forwarding page (in the router's configuration page) add a entry that forwards the external requests to a specific address in your LAN.

Server and Java Applet: Connecting Socket

I have a java applet recently stopped working after the server is updated, more specifically:
1. The server is updated from Sun, running Solaris 9, 32 bit. (installed in 2005) to CentOS 5, (linux) on 64 bit.
2. The applet has two major classes 1) collect.class: collects data from a canvas 2) server.class: listens to collect.class through a PORT and acts accordingly;
but the applet got stuck and I check the start_server.sh (which produces a report nohup.out) there is a line
Exception creating server socket: java.net.BindException: Address already in use
This is weird, because PORT = 9999 which collect.class uses with no problem. How comes the problem happens only in server.class (who listens to collet.class).
Please help!
ADDITIONAL INFORMATION:
I.IN COLLECT.JAVA:
There is a canvas with grid on it, the user draw some area on the grid and click "Submit".
-> The MineCanvas.submit() is triggered -> The value of the area is computed by MineCanvas.ComputeGridValue() -> then Collect.cleintSend (stuck here)
import java.applet.*;
import java.awt.*;
import java.net.*;
import java.io.*;
import java.util.*;
public class Collect extends Applet {
...
public static final int PORT = 8888;
...
public boolean action(Event e, Object arg) {
...
if (arg.equals("Submit")) {
if (action(null, "Update Grid")) {
minecanvas.Submit();
} else {
return true;
}
}
return true;
}
...
public void clientSend(){
s = new Socket(this.getCodeBase().getHost(), PORT);
in = new DataInputStream(s.getInputStream());}
out = new DataOutputStream(s.getOutputStream());
listener = new SolutionListener(in, minecanvas);}
minecanvas.mode = MineCanvas.SUBMITTING;
minecanvas.repaint();
int n = 1;
out.writeBytes(minecanvas.gridh + "\n" + minecanvas.gridw + "\n");
for (int h = 0; h < minecanvas.gridh; h++) {
for (int w = 0; w < minecanvas.gridw; w++) {
out.writeBytes(n + " " + minecanvas.AllCells[w][h].net + "\n");
n++;
}
}
out.writeBytes("done\n");
s = null;
in = null;
out = null;
}
}
class MineCanvas extends Canvas {
...
public int gridw = 0; // number of grid squares width-ly
public int gridh = 0; // number of grid squares height-ly
public GridCell[][] AllCells; // array of grid cells comprising the grid
...
// compute values for minecanvas
public void ComputeGridValue() {...}
public void Submit() {
ComputeGridValue();
parent.clientSend();
}
...
}
...
}
II. SERVER.JAVA
import java.io.*;
import java.net.*;
public class Server extends Thread {
private OPM_Server opm; // this is the corresponding server for collect
...
public Server() {
...
opm = new OPM_Server();
}
public static void main(String[] args) {
new Server();
}
}
...
// OPM: correspond to Collect
class OPM_Server extends Thread {
public final static int DEFAULT_PORT = 8888;
protected int port;
protected ServerSocket listen_socket;
public static void fail(Exception e, String msg) {
System.err.println(msg + ": " + e);
System.exit(1);
}
public OPM_Server() {
this.port = DEFAULT_PORT;
try { listen_socket = new ServerSocket(port); }
catch (IOException e){ fail(e, "Exception creating server socket");}
System.out.println("Server: listening on port " + port);
this.start();
}
public void run() {
try {
while(true) {
System.out.println("I got to before ServerSocket");
Socket client_socket = listen_socket.accept();
OPM_Connection c = new OPM_Connection(client_socket);
}
}
catch (IOException e) {fail(e, "Exception while listening for connections");}
}
}
...
class OPM_Connection extends Thread {
protected Socket client;
protected BufferedReader in;
protected DataOutputStream out;
File mine_data = new File("mine_data"); // output file data
FileOutputStream file_stream;
DataOutputStream file_out;
public OPM_Connection(Socket client_socket) {
client = client_socket;
try {
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new DataOutputStream(client.getOutputStream());
} catch (IOException e) {
try {
client.close();
} catch (IOException e2) {
}
;
System.err.println("Exception while getting socket stream: "
+ e.toString());
return;
}
this.start();
}
public void run() {
...
file_stream = new FileOutputStream(mine_data);
file_out = new DataOutputStream(file_stream);
...// write to mine data
file_out = null;
if (inputGood == true) {
System.out.println(pid + "> ---Got all info from client");
Runtime r = Runtime.getRuntime();
Process Aproc = null;
Process Bproc = null;
int returnVal = -1;
try {
Aproc = r.exec("runOPM");
} catch (IOException e) {
inputGood = false;
System.out.println(pid + "> runOPM didn't exec");
}
try {
returnVal = Aproc.waitFor();
} catch (InterruptedException e) {
inputGood = false;
System.out.println(pid + "> runOPM didn't return");
}
System.out.println(pid + "> ---All execing done");
File report = new File("mine_report");
FileInputStream report_stream = null;
...
// create a mine report
System.out.println(pid + "> ---Done sending data back to client");
}
try {
client.close();
} catch (IOException e2) {
}
;
System.out.println(pid + "> EXITING THREAD");
}
}
Exception creating server socket: java.net.BindException: Address
already in use
This exception means that the port number the socket is trying to bind to (the port number your socket is trying to use in the local-end of the connection) is already in use by some other program. To fix it, you either need to find out what other software is using the port and see if you can safely change it, or change the port your program is using.
Edit: It might be worth trying to look for rarely used port(s), to lessen the chance of using yet another port that is known to be used by some common software, here's Wikipedias list of typical TCP and UDP ports in use by common programs and services.

Show previous instance of RCP application

I had an rcp application which runs for only first run, when a user attempts to re-execute the application, second instance behaves as a client which encodes and sends its arguments over the socket to the first instance which acts as a server and then exits silently. The first instance receives and decodes that message, then behaves as if it had been invoked with those arguments.
so far so good i made internal protocol specification for passing arguments between two instances.
I could not bring the first instance(RCP application) to front. It is in minimized state only,
this is in continuation to my previous question
the change i made to previous post is start method of application class
public Object start(IApplicationContext context) throws Exception {
if (!ApplicationInstanceManager.registerInstance()) {
return IApplication.EXIT_OK;
}
ApplicationInstanceManager
.setApplicationInstanceListener(new ApplicationInstanceListener() {
public void newInstanceCreated() {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
System.out.println("New instance detected...");
//Display.getCurrent().getActiveShell()
.forceActive();// this gives null
// pointer exception
// hence commented
}
});
}
});
Display display = PlatformUI.createDisplay();
try {
int returnCode = PlatformUI.createAndRunWorkbench(display,
new ApplicationWorkbenchAdvisor());
if (returnCode == PlatformUI.RETURN_RESTART)
return IApplication.EXIT_RESTART;
else
return IApplication.EXIT_OK;
} finally {
display.dispose();
}
}
below line is stopping me to bring Application to front
Display.getCurrent().getActiveShell().forceActive();
generates null pointer exception at getActiveShell()
how can i maximize the previous instance or bring it to front
I wrote an instance manager to restrict my RCP to a single instance.
Here's the code that goes in Application.java, in the start method:
if (!ApplicationInstanceManager.registerInstance()) {
return IApplication.EXIT_OK;
}
ApplicationInstanceManager
.setApplicationInstanceListener(new ApplicationInstanceListener() {
public void newInstanceCreated() {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
if (DEBUG)
System.out.println("New instance detected...");
Display.getCurrent().getActiveShell().forceActive();
}
});
}
});
Here's the listener interface:
public interface ApplicationInstanceListener {
public void newInstanceCreated();
}
And here's the Manager class:
public class ApplicationInstanceManager {
private static final boolean DEBUG = true;
private static ApplicationInstanceListener subListener;
/** Randomly chosen, but static, high socket number */
public static final int SINGLE_INSTANCE_NETWORK_SOCKET = 44331;
/** Must end with newline */
public static final String SINGLE_INSTANCE_SHARED_KEY = "$$RabidNewInstance$$\n";
/**
* Registers this instance of the application.
*
* #return true if first instance, false if not.
*/
public static boolean registerInstance() {
// returnValueOnError should be true if lenient (allows app to run on
// network error) or false if strict.
boolean returnValueOnError = true;
// try to open network socket
// if success, listen to socket for new instance message, return true
// if unable to open, connect to existing and send new instance message,
// return false
try {
final ServerSocket socket = new ServerSocket(
SINGLE_INSTANCE_NETWORK_SOCKET, 10, InetAddress
.getLocalHost());
if (DEBUG)
System.out
.println("Listening for application instances on socket "
+ SINGLE_INSTANCE_NETWORK_SOCKET);
Thread instanceListenerThread = new InstanceListenerThread(socket);
instanceListenerThread.start();
// listen
} catch (UnknownHostException e) {
EclipseLogging.logError(RabidPlugin.getDefault(),
RabidPlugin.PLUGIN_ID, e);
return returnValueOnError;
} catch (IOException e) {
return portTaken(returnValueOnError, e);
}
return true;
}
private static boolean portTaken(boolean returnValueOnError, IOException e) {
if (DEBUG)
System.out.println("Port is already taken. "
+ "Notifying first instance.");
try {
Socket clientSocket = new Socket(InetAddress.getLocalHost(),
SINGLE_INSTANCE_NETWORK_SOCKET);
OutputStream out = clientSocket.getOutputStream();
out.write(SINGLE_INSTANCE_SHARED_KEY.getBytes());
out.close();
clientSocket.close();
System.out.println("Successfully notified first instance.");
return false;
} catch (UnknownHostException e1) {
EclipseLogging.logError(RabidPlugin.getDefault(),
RabidPlugin.PLUGIN_ID, e);
return returnValueOnError;
} catch (IOException e1) {
EclipseLogging
.logError(
RabidPlugin.getDefault(),
RabidPlugin.PLUGIN_ID,
"Error connecting to local port for single instance notification",
e);
return returnValueOnError;
}
}
public static void setApplicationInstanceListener(
ApplicationInstanceListener listener) {
subListener = listener;
}
private static void fireNewInstance() {
if (subListener != null) {
subListener.newInstanceCreated();
}
}
public static void main(String[] args) {
if (!ApplicationInstanceManager.registerInstance()) {
// instance already running.
System.out.println("Another instance of this application "
+ "is already running. Exiting.");
System.exit(0);
}
ApplicationInstanceManager
.setApplicationInstanceListener(new ApplicationInstanceListener() {
public void newInstanceCreated() {
System.out.println("New instance detected...");
// this is where your handler code goes...
}
});
}
public static class InstanceListenerThread extends Thread {
private ServerSocket socket;
public InstanceListenerThread(ServerSocket socket) {
this.socket = socket;
}
#Override
public void run() {
boolean socketClosed = false;
while (!socketClosed) {
if (socket.isClosed()) {
socketClosed = true;
} else {
try {
Socket client = socket.accept();
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
String message = in.readLine();
if (SINGLE_INSTANCE_SHARED_KEY.trim().equals(
message.trim())) {
if (DEBUG)
System.out.println("Shared key matched - "
+ "new application instance found");
fireNewInstance();
}
in.close();
client.close();
} catch (IOException e) {
socketClosed = true;
}
}
}
}
}
}
After your IApplication start up, you can also check and lock the OSGi instance location using org.eclipse.osgi.service.datalocation.Location.isSet() and org.eclipse.osgi.service.datalocation.Location.lock()
The location is usually retrieved from your Activator using code like:
public Location getInstanceLocation() {
if (locationTracker == null) {
Filter filter = null;
try {
filter = context.createFilter(Location.INSTANCE_FILTER);
} catch (InvalidSyntaxException e) {
// ignore this. It should never happen as we have tested the
// above format.
}
locationTracker = new ServiceTracker(context, filter, null);
locationTracker.open();
}
return (Location) locationTracker.getService();
}