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
}
}
Related
I have a simple netty connection pool and a simple HTTP endpoint to use that pool to send TCP messages to ServerSocket. The relevant code looks like this, the client (NettyConnectionPoolClientApplication) is:
#SpringBootApplication
#RestController
public class NettyConnectionPoolClientApplication {
private SimpleChannelPool simpleChannelPool;
public static void main(String[] args) {
SpringApplication.run(NettyConnectionPoolClientApplication.class, args);
}
#PostConstruct
public void setup() throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group);
bootstrap.channel(NioSocketChannel.class);
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
bootstrap.remoteAddress(new InetSocketAddress("localhost", 9000));
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
pipeline.addLast(new StringDecoder());
pipeline.addLast(new StringEncoder());
pipeline.addLast(new DummyClientHandler());
}
});
simpleChannelPool = new SimpleChannelPool(bootstrap, new DummyChannelPoolHandler());
}
#RequestMapping("/test/{msg}")
public void test(#PathVariable String msg) throws Exception {
Future<Channel> future = simpleChannelPool.acquire();
future.addListener((FutureListener<Channel>) f -> {
if (f.isSuccess()) {
System.out.println("Connected");
Channel ch = f.getNow();
ch.writeAndFlush(msg + System.lineSeparator());
// Release back to pool
simpleChannelPool.release(ch);
} else {
System.out.println("not successful");
}
});
}
}
and the Server (ServerSocketRunner)
public class ServerSocketRunner {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(9000);
while (true) {
Socket socket = serverSocket.accept();
new Thread(() -> {
System.out.println("New client connected");
try (PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));) {
String inputLine, outputLine;
out.println("Hello client!");
do {
inputLine = in.readLine();
System.out.println("Received: " + inputLine);
} while (!"bye".equals(inputLine));
System.out.println("Closing connection...");
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
}
}
DummyChannelPoolHandler and DummyClientHandler just print out events that happen, so they are not relevant. When the server and the client are started and I send a test message to test endpoint, I can see the server prints "New client connected" but the message sent by client is not printed. None of the consecutive messages sent by client are printed by the server.
If I try telnet, everything works fine, the server prints out messages. Also it works fine with regular netty client with same bootstrap config and without connection pool (SimpleNettyClientApplication).
Can anyone see what is wrong with my connection pool, I'm out of ideas
Netty versioin: 4.1.39.Final
All the code is available here.
UPDATE
Following Norman Maurer advice. I added
ChannelFuture channelFuture = ch
.writeAndFlush(msg + System.lineSeparator());
channelFuture.addListener(writeFuture -> {
System.out
.println("isSuccess(): " + channelFuture.isSuccess() + " : " + channelFuture.cause());
});
This prints out
isSuccess: false : java.lang.UnsupportedOperationException: unsupported message type: String (expected: ByteBuf, FileRegion)
To fix it, I just converted String into ByteBuf
ch.writeAndFlush(Unpooled.wrappedBuffer((msg + System.lineSeparator()).getBytes()));
You should check what the status of the ChannelFuture is that is returned by writeAndFlush(...). I suspect it is failed.
I am running Netty 4.2 socket communication code with ssl (self signed certificate).
My Problem:
When client tries to connect to server with SSL, server immediately drops the connection. Server triggers channelUnregistered() method immediately.
One point I noticed is, very first time once the server started, client connection holds and works fine. But when client disconnects and try to connect to Server again, it drops the connection immediately.
But without SSL it works fine without any issues.
Client Code:
public Channel initializeNettySocket()
{
group = new NioEventLoopGroup();
try
{
ClientAdapterInitializer clientAdapterInitializer = null;
if (ServerSettings.isUseSSL())
{
// SSLEngine engine = SSLContextFactory.getClientContext().createSSLEngine();
SSLEngine engine = SSLContext.getDefault().createSSLEngine(host,port);
engine.setUseClientMode(true);
clientAdapterInitializer = new ClientAdapterInitializer(engine);
}
else
{
clientAdapterInitializer = new ClientAdapterInitializer();
}
Bootstrap bootstrap = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(clientAdapterInitializer);
channel = bootstrap.connect(host,port).sync().channel();
Thread.sleep(3000);
setChannel(channel);
}
catch (Exception e)
{
System.out.println(e.getMessage());
e.printStackTrace();
}
return channel;
}
public class ClientAdapterInitializer extends ChannelInitializer<SocketChannel>
{
private SSLEngine sslCtx = null;
public ClientAdapterInitializer(SSLEngine sslCtx)
{
this.sslCtx = sslCtx;
}
public ClientAdapterInitializer()
{
}
#Override
protected void initChannel(SocketChannel channel) throws Exception
{
ChannelPipeline pipeline = channel.pipeline();
if (ServerSettings.isUseSSL())
{
// Add SSL handler first to encrypt and decrypt everything.
// In this example, we use a bogus certificate in the server side
// and accept any invalid certificates in the client side.
// You will need something more complicated to identify both
// and server in the real world.
//pipeline.addLast(sslCtx.newHandler(ch.alloc(), SecureChatClient.HOST, SecureChatClient.PORT));
pipeline.addLast(new SslHandler(sslCtx));
}
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast("handler", new ClientAdapterHandler());
}
Server side code
public class ServerAdapterInitializer extends ChannelInitializer<SocketChannel>
{
private SSLEngine sslEngine;
public ServerAdapterInitializer(SSLEngine sslEngine)
{
this.sslEngine = sslEngine;
}
public ServerAdapterInitializer()
{
}
#Override
protected void initChannel(SocketChannel channel) throws Exception
{
ChannelPipeline pipeline = channel.pipeline();
if (sslEngine != null)
{
pipeline.addLast(new SslHandler(sslEngine));
}
Listeners.getInstance().getAllListeners().size();
RTReceiverAdapterHandler rtReceiverAdapterHandler = new RTReceiverAdapterHandler();
pipeline.addLast("idleStateHandler", new IdleStateHandler(0, 0, 10)); // add
// with
// name
pipeline.addLast("decoder", new MyStringDecoder(rtReceiverAdapterHandler));
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast("handler", rtReceiverAdapterHandler);
}
}
public class RTReceiverAdapterHandler extends ChannelInboundHandlerAdapter
{
#Override
public void channelActive(ChannelHandlerContext ctx) throws Exception
{
if (ServerSettings.isUseSSL())
{
// Once session is secured, send a greeting and register the channel
// to the global channel
// list so the channel received the messages from others.
ctx.pipeline().get(SslHandler.class).handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>()
{
#Override
public void operationComplete(Future<Channel> future) throws Exception
{
ctx.writeAndFlush("Welcome!\n");
ctx.writeAndFlush("Your session is protected by " + ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite()
+ " cipher suite.\n");
channels.add(ctx.channel());
}
});
}
else
{
super.channelActive(ctx);
}
}
}
The problem was not with the code at all. We have nginx web server configured with SSL before my application. This entry in nginx 'ssl_ciphers AES256+EECDH:AES256+EDH:!aNULL;' was the culprit which was not allowing to access the netty server.
I commented the above entry in ngnix and my problem was resolved.
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
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.
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.