孤独不是寂寞 2015-10-12 06:02 采纳率: 40%
浏览 2193
已采纳

java中怎么在一台机子上实现多个用户之间的信息交流,类似聊天室使用UDP数据报

package NetAdressDC;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class liaotianshi2 {

/**
 * @param args
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    System.out.println("kasiihi");

    DatagramSocket ds = new DatagramSocket(6000);
    DatagramSocket ds1 = new DatagramSocket(7000);
    new Thread(new send2(ds)).start();
    new Thread(new rece2(ds1)).start();

}

}
class send2 implements Runnable {

private DatagramSocket ds;

public send2(DatagramSocket ds) {
    super();
    this.ds = ds;
}

public void run() {
    // TODO Auto-generated method stub
    System.out.println("聊天开始");

    try {

        BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
        String str = null;

        while((str=bufr.readLine())!=null)
        {
            if("over".equals(str))
            {break;}
            byte[] by = str.getBytes();
     //System.out.println(str);
            DatagramPacket dg = new DatagramPacket(by, by.length,InetAddress.getByName("172.24.118.1"),7000);
            ds.send(dg);

        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

}
class rece2 implements Runnable {
private DatagramSocket ds1;

public rece2(DatagramSocket ds1) {
    super();
    this.ds1 = ds1;
}
public void run() {
    // TODO Auto-generated method stub

while(true){

        byte[] buf = new byte[1024];
        DatagramPacket dp = new DatagramPacket(buf,buf.length);

        try {
            ds1.receive(dp);


            String ip  = dp.getAddress().getHostAddress();
            String text = new String(dp.getData(),0,dp.getLength());

            System.out.println(ip+"::"+text);
            if("88".equals(text)){
                System.out.println(ip+".....离开聊天室!!!");
            }
        } catch (IOException e) {

            e.printStackTrace();
        }

}
}
}
我是想在一台电脑上开几个控制台模拟进行多台电脑进行局域网之间的交流,但是不行,感觉应该是端口设置或者ip地址的写法有问题,求大神解,应该怎么写才能实现

  • 写回答

2条回答

  • 孤独不是寂寞 2015-10-12 08:07
    关注

    。。。。。。已解决,谢谢

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果