2 qq 26169787 qq_26169787 于 2016.03.30 15:36 提问

java socket绑定 255 广播地址异常

绑定192.168.0.255时出现异常,改成127.0.0.1时可以正常运行,不知道为什么

 public class Tel implements Runnable{

    public static void main(String[] args) {

        Tel tel = new Tel();

        new Thread(tel).start();

        try {
            Socket socket = new Socket("192.168.0.255",9090);
            OutputStream os = socket.getOutputStream();
            Scanner in = new Scanner(System.in);
            String str = in.nextLine();
            while(!str.equals("over")){
                os.write(str.getBytes());
                str = in.nextLine();
            }
            in.close();
            socket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }

    public void run() {
        ServerSocket service;
        try {
            service = new ServerSocket(9090);
            Socket socket = service.accept();
            InputStream in = socket.getInputStream();
            byte[] buf = new byte[1024];
            int len = -1;
            while(true){
                while((len = in.read(buf))!=-1){
                    System.out.println(new String(buf,0,len));
                }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

 java.net.ConnectException: connect: Address is invalid on local machine, or port is not valid on remote machine
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at java.net.Socket.connect(Socket.java:538)
    at java.net.Socket.<init>(Socket.java:434)
    at java.net.Socket.<init>(Socket.java:211)
    at test.Tel.main(Tel.java:19)

2个回答

magoo_up
magoo_up   2016.03.30 16:36

Socket对应的是TCP是不能广播的,要用广播的话使用DatagramSocket (UDP)

qq_26169787
qq_26169787 回复qq_26169787: 谢谢了
一年多之前 回复
qq_26169787
qq_26169787 嗯,就是需要用DatagramSocket。 用DatagramPacket创建数据包,然后用DatagramSocket发送就好了。
一年多之前 回复
u012436479
u012436479   2016.03.30 16:28

.255的是广播地址, 这种地址作为保留地址不能使用吧,这算是路由发送广播的地址吧。
127.0.0.1是回送地址,相当于是你本机的IP。你能给你本机发送信息当然能正常。

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!