Java Socket Server和C#客户端Localhost可以工作

时间:2018-10-03 14:03:39

标签: java c# sockets

我在C#中有一个客户端,该客户端将数据发送到Java异步服务器并在 localhost中将数据写入GUI中,一切正常,但是当我更改为其他IP时,该客户端对我说:

  

System.Net.Sockets.SocketException(0x80004005):无法建立连接,因为目标设备明确拒绝了此类连接192.168.1.172:11000      zh-cn System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot,SocketAddress socketAddress)      zh-CN System.Net.Sockets.Socket.Connect(EndPoint remoteEP)

客户端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服务器:

    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();
    }

为什么它只能在本地主机上工作?

1 个答案:

答案 0 :(得分:2)

好吧,您只绑定到localhost。您应该使用要绑定的实际IP地址。

您还可以尝试通过以下方式绑定到所有IPv4接口:

InetSocketAddress sAddr = new InetSocketAddress("0.0.0.0", port);
server.bind(sAddr);