本人接触JAVA 一个多月了 自己写了个 局域网聊天 传文件 和群聊的小软件。群聊不是用的服务器客户端的模式,而是直接在局域网中用 multiCastSocket进行广播。但是 自己的机器上不管能收到广播,在局域网其他的机器上就收不到。也在网上查了很久,没找到相似的情况。纠结了两天了。于是想在这里来问问大家 代码很长  我贴出个我广播自己在线,和在线用户查询的代码。//广播自己在线的类package lMess;//服务端代码:不断广播--自身信息import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.*;public class BroadCast extends Thread { String message; int port = 50611; InetAddress group = null; MulticastSocket socket = null;
private javax.swing.JTextField userNameArea;
String ip; BroadCast(javax.swing.JTextField userNameArea) {
this.userNameArea = userNameArea;
File ipFile = new File("ipBroadCast.ini");
try {
if (ipFile.exists()) {
BufferedReader reader = new BufferedReader(new FileReader(
"ipBroadCast.ini"));
try {
ip = reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
group = InetAddress.getByName(ip);
socket = new MulticastSocket(port);
socket.setTimeToLive(0);
socket.joinGroup(group); } catch (Exception e) {
}
} public void run() {
while (true) {
try {
DatagramPacket packet = null;
message = "USER:" + userNameArea.getText() + " @ "
+ InetAddress.getLocalHost();
byte data[] = message.getBytes();
packet = new DatagramPacket(data, data.length, group, port);
System.out.println(new String(data));
socket.send(packet);
sleep(4000);
} catch (Exception e) {
}
}
}}//接受广播的类package lMess;import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;import javax.swing.JButton;
import javax.swing.JTextArea;public class UsersFinding implements Runnable { private javax.swing.JTextArea usersList; int port = 50611;
InetAddress group = null;
MulticastSocket socket = null;
JButton startReceive, stopReceive;
JTextArea showArea;
Thread thread;
boolean stop = false;
String ip; public UsersFinding(javax.swing.JTextArea usersList) {
this.usersList = usersList;
File ipFile = new File("ipBroadCast.ini");
try {
if (ipFile.exists()) {
BufferedReader reader = new BufferedReader(new FileReader(
"ipBroadCast.ini"));
try {
ip = reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} public void run() { try {
while (true) {
group = InetAddress.getByName(ip);
socket = new MulticastSocket(port);
socket.joinGroup(group);
byte[] buffer = new byte[256];
DatagramPacket dgp = new DatagramPacket(buffer, buffer.length);
socket.receive(dgp);
byte[] getMessage = new byte[dgp.getLength()];
System.arraycopy(dgp.getData(), 0, getMessage, 0,
dgp.getLength()); String get = new String(getMessage);
System.out.println("UsersFinding get the Message:\n" + get); if (get.indexOf("USER") == 0) {// 说明是用户信息 获取
if (this.usersList.getText().indexOf(get) < 0) {
this.usersList.append(get + "\n");
}
} if (get.indexOf("LEAVE") == 0) {
String date = get
.substring("LEAVE:".length(), get.length());
String list = this.usersList.getText();
this.usersList
.setText(list.substring(0, list.indexOf(date))
+ list.substring(
list.indexOf(date) + date.length(),
list.length()));
} if (get.indexOf("CHANGE") == 0) {// 删除操作 同上
String date = get.substring("CHANGE:".length(),
get.length());
String list = this.usersList.getText();
this.usersList
.setText(list.substring(0, list.indexOf(date))
+ list.substring(
list.indexOf(date) + date.length(),
list.length()));
} }
} catch (Exception e) {
e.printStackTrace();
} }
}
大家谁能帮我看看。新手 很多东西不是很懂。第一次用CSDN 也不知道积分是什么东西。也不知道自己有没有积分,默认值是40 就设个40.希望好心人帮我解答一下问题。积分我有一定给。谢谢大家了。

解决方案 »

  1.   

    恩 我用的ipBroadCast.ini 文件设置的IP  确实设置的是D类IP 而且是一般的局域网的那个广播地址 貌似不行。用224.0.0.0-239.255.255.255 之间的才能在自己机器上收到 但是 机器收不到
      

  2.   

    你得自己架了局域网!如果你通过ISP的路由器!它肯定不会让你广播的!
      

  3.   

    楼主,可能是你的ttl有问题吧socket.setTimeToLive(0);你把0改为255试试
      

  4.   

    额 7楼说的是,这个SSL 我倒是想到过的 只是没注意自己设的是0 改成1就OK了。
      

  5.   

    我也遇到这样的问题,在网上找了一些试了一下,在一台机器上开多个客户端是可以,但是同一局域网中两台PC之间就是不行,这里已经s.setTimeToLive(1),期待回答
    import java.net.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    public class MutilCast {
        public static void main(String[] args)
        {
            MulticastSocket s              = null;
            InetAddress group               = null;    
            JPanel northPanel               =new JPanel();   
            JPanel southPanel               =new JPanel();
            JPanel namePanel                =new JPanel(new FlowLayout());
            JLabel sendLabel                =new JLabel("发送内容:");
            JLabel nameChangeLabel          =new JLabel("给自己起个名字:");
    final    JTextField nameSpace           =new JTextField(20);
    final    JTextArea messageArea          =new JTextArea("",20,20);
    final    JTextField sendField            =new JTextField(30);
            JScrollPane message              =new JScrollPane(messageArea);
            JButton sendButton               =new JButton("发送");
            JButton saveButton               =new JButton("保存记录");
            JButton clearUpButton            =new JButton("清空面板");
            Box    centerBox                  =Box.createVerticalBox();
            namePanel.add(nameChangeLabel);
            namePanel.add(nameSpace);
            centerBox.add(namePanel);
            centerBox.add(message);   
          //实现组播数据传送的配置信息
            try {
                 group = InetAddress.getByName("228.9.6.8");
            } catch (UnknownHostException e1) {
                System.out.println("组播地址绑定失败");
            }      
            try {
                s = new MulticastSocket(6789);
                s.setTimeToLive(1);
            } catch (IOException e1) {
                System.out.println("组播地址创建失败");
            }
            try {
                    s.joinGroup(group);
            } catch (IOException e1) {
                System.out.println("组播地址加入失败");
            }
          //end实现组播数据传送的配置信息
          //“发送”按钮实现信息功能的发送部分                  
            class SendMsg implements ActionListener
            {
                String msg=null;         
                MulticastSocket s=null;
                InetAddress group = null;
                public SendMsg(MulticastSocket s,InetAddress group)
                {
                    this.s=s;
                    this.group=group;
                }
                public void actionPerformed(ActionEvent e)
                {              
                     try
                    {
                         //如果名字为空 给出提示信息
                        if(nameSpace.getText().isEmpty())                   
                            new JOptionPane().showMessageDialog(null, "请一定要取别名!");
                        else
                        {
                        //如果名字不为空 则把名字添加到数据报头
                        msg=(nameSpace.getText()+"说:"+sendField.getText());
    DatagramPacket data=
     new DatagramPacket(msg.getBytes(),msg.getBytes().length,group, 6789);
                        s.send(data);
                        }
                     }
                     catch (IOException e1) {
                        System.out.println("发送失败");
                    }      
                }
            }
             //实现数据报的接受线程      
            class  recevMsg extends Thread
            {
                 MulticastSocket s=null;
                 public recevMsg(MulticastSocket s)
                 {
                     this.s=s;
                 };
                 public void run()
                 {
                     byte[] buf = new byte[100];
                    DatagramPacket recv = new DatagramPacket(buf, buf.length);
                     try
                     {
                         while(true)
                         {
                             s.receive(recv);
                             String str=new String(recv.getData());
                              String line =System.getProperty("line.separator");
                             messageArea.append(str);
                             messageArea.append(line);
                         }
                     }
                     catch (IOException e1)
                     {
                         System.out.println("接受失败");
                     }
                 }
            }
           //聊天记录的保存 保存在当前位置下的"Note.txt"文件中
            class SaveMsg implements ActionListener
            {
                String msg=null;
                String line =System.getProperty("line.separator");
                public void actionPerformed(ActionEvent e)
                {              
                     try
                     {
                        msg=messageArea.getText();
                         FileOutputStream Note=new FileOutputStream("Note.txt");
                        messageArea.append("记录已经保存在Note.txt");
                        Note.write(msg.getBytes());
                        messageArea.append(line);
                        Note.close();
                     }
                     catch (IOException e1) {
                        System.out.println("发送失败");
                    }      
                }
            }
            //清除面板上的聊天记录
            class ClearMsg implements ActionListener
            {
                public void actionPerformed(ActionEvent e)
                {              
                     try
                     {
                         messageArea.setText("");
                     }
                     catch (Exception e1) {
                        System.out.println("清空失败");
                    }      
                }
            }
            JFrame mutilCastFrame=new JFrame("组播聊天工具");
            northPanel.add(sendLabel);
            northPanel.add(sendField);
            northPanel.add(sendButton);
            southPanel.add(saveButton);
            southPanel.add(clearUpButton);
            mutilCastFrame.getContentPane().add(northPanel,"North");
            mutilCastFrame.getContentPane().add(southPanel,"South");  
            mutilCastFrame.getContentPane().add(centerBox,"Center");
    mutilCastFrame.setDefaultCloseOperation(mutilCastFrame.EXIT_ON_CLOSE); 
    sendButton.addActionListener(new SendMsg(s,group));
            saveButton.addActionListener(new SaveMsg());
            clearUpButton.addActionListener(new ClearMsg());
            mutilCastFrame.setSize(500, 500);
            mutilCastFrame.setLocation(200, 200);
            mutilCastFrame.show();
            recevMsg r=new recevMsg(s);
            r.start();
            }
    }