0

I have a Client in C# Who send the data to a Java Asynchronous Server and write the data in a GUI, in localhost all it is ok but, when I change to other ip, the client says me:

System.Net.Sockets.SocketException (0x80004005): Unable to establish a connection since the destination equipment expressly denied such connection 192.168.1.172:11000 en System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) en System.Net.Sockets.Socket.Connect(EndPoint remoteEP)

Client C#:

public void StartClient(string precio)
    {
        // Data buffer for incoming data.  
        byte[] bytes = new byte[1024];

        // Connect to a remote device.  
        try
        {

            IPAddress ipAddress = IPAddress.Parse("192.168.1.172");
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);

            // Create a TCP/IP  socket.  
            Socket sender = new Socket(ipAddress.AddressFamily,
                SocketType.Stream, ProtocolType.Tcp);

            // Connect the socket to the remote endpoint. Catch any errors.  
            try
            {
                sender.Connect(remoteEP);

                Console.WriteLine("Socket connected to {0}",
                    sender.RemoteEndPoint.ToString());

                // Encode the data string into a byte array.  
                byte[] msg = Encoding.ASCII.GetBytes(precio + "<EOF>");
                Console.WriteLine(msg);
                // Send the data through the socket.  
                int bytesSent = sender.Send(msg);

                // Release the socket.  
                sender.Shutdown(SocketShutdown.Both);
                sender.Close();

            }
            catch (ArgumentNullException ane)
            {
                Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
            }
            catch (SocketException se)
            {
                Console.WriteLine("SocketException : {0}", se.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Unexpected exception : {0}", e.ToString());
            }

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

Java Server:

    private void init() throws IOException, InterruptedException {
        AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open();//w w w  .  j  a  v  a2s .com
        String host = "127.0.0.1";
        int port = 11000;
        InetSocketAddress sAddr = new InetSocketAddress(host, port);
        server.bind(sAddr);
        System.out.format("Server is listening at %s%n", sAddr);
        Attachment attach = new Attachment();
        attach.server = server;
        server.accept(attach, new ConnectionHandler());
        //Thread.currentThread().join();
    }


}
class Attachment {
    AsynchronousServerSocketChannel server;
    AsynchronousSocketChannel client;
    ByteBuffer buffer;
    SocketAddress clientAddr;
    boolean isRead;
}

class ConnectionHandler implements
        CompletionHandler<AsynchronousSocketChannel, Attachment> {
    @Override
    public void completed(AsynchronousSocketChannel client, Attachment attach) {
        try {
            SocketAddress clientAddr = client.getRemoteAddress();
            System.out.format("Accepted a  connection from  %s%n", clientAddr);
            attach.server.accept(attach, this);
            ReadWriteHandler rwHandler = new ReadWriteHandler();
            Attachment newAttach = new Attachment();
            newAttach.server = attach.server;
            newAttach.client = client;
            newAttach.buffer = ByteBuffer.allocate(2048);
            newAttach.isRead = true;
            newAttach.clientAddr = clientAddr;
            client.read(newAttach.buffer, newAttach, rwHandler);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void failed(Throwable e, Attachment attach) {
        System.out.println("Failed to accept a  connection.");
        e.printStackTrace();
    }
}

class ReadWriteHandler implements CompletionHandler<Integer, Attachment> {
    @Override
    public void completed(Integer result, Attachment attach) {
        if (result == -1) {
            try {
                attach.client.close();
                System.out.format("Stopped   listening to the   client %s%n",
                        attach.clientAddr);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            return;
        }

        if (attach.isRead) {
            attach.buffer.flip();
            int limits = attach.buffer.limit();
            byte bytes[] = new byte[limits];
            attach.buffer.get(bytes, 0, limits);
            Charset cs = Charset.forName("UTF-8");
            String msg = new String(bytes, cs);
            if (msg.contains("<EOF>")){
                //System.out.println("es Total");
                Servidor.total = msg.substring(0,msg.indexOf("<"));
                Servidor.formEntrada.setLabelTotal(Servidor.total);
                Servidor.total = Servidor.total.replace(",",".");
                //onSendData.onSendDataTotal();
            }else if (msg.contains("<REC>")) {
                //System.out.println("es Cobro");
                Servidor.enviado = msg.substring(0, msg.indexOf("<"));
                Servidor.formEntrada.setLabelEnviado(Servidor.enviado);
                Servidor.enviado = Servidor.enviado.replace(",", ".");
                if (Double.parseDouble(Servidor.enviado) >= Double.parseDouble(Servidor.total)) {
                    Servidor.formEntrada.setRestoValue(Servidor.total, Servidor.enviado);
                }
            }
            System.out.format("Client at  %s  says: %s%n", attach.clientAddr,
                    msg);
            attach.isRead = false; // It is a write
            attach.buffer.rewind();

        } else {
            // Write to the client
            attach.client.write(attach.buffer, attach, this);
            attach.isRead = true;
            attach.buffer.clear();
            attach.client.read(attach.buffer, attach, this);
        }
    }

    @Override
    public void failed(Throwable e, Attachment attach) {
        e.printStackTrace();
    }

Why it works only in localhost?

0

1 Answer 1

1

Well you're only binding to localhost. You should use the actual IP address you want to bind to.

You could also try binding to all IPv4 interfaces with:

InetSocketAddress sAddr = new InetSocketAddress("0.0.0.0", port);
server.bind(sAddr);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.