java實現簡單聊天室

  • 僅供初學者瀏覽,自娛自樂代碼。如有不足,還請指出。
package groupChat;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class ServerTest {
    static Map<InetAddress,Integer> map=new HashMap<InetAddress,Integer>();

    public static void main(String[] args) throws SocketException, UnknownHostException {
        //創建map  鍵放入ip,值放入端口號
        DatagramSocket  ds=new DatagramSocket(9999);
        while(true){
            byte [] b=new byte[1024];
            DatagramPacket dp=new DatagramPacket(b, b.length);
            try {
                ds.receive(dp);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //獲得對方的ip
            InetAddress add=dp.getAddress();
            //判斷是否存在
            if(check(add,dp.getPort())){
                //不存在就存入ip和端口
                map.put(add, dp.getPort());
            }
            //拼接準備發送信息
            String message="ip:"+add.getHostAddress()+":"+dp.getPort()+"="+new String(dp.getData(),0,dp.getLength());
            System.out.println(message);
            new Thread(new SendTest(map,message)).start();

        }

    }
    //判斷集合內是否已有用戶
    public static boolean check(InetAddress add,int port){
        for(Entry<InetAddress, Integer> en:map.entrySet()){
             if(en.getKey().getHostAddress().equals(add.getHostAddress())&&en.getValue().equals(port)){
                return false;
             }
        }
        return true;
    }


}
package groupChat;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Map;
import java.util.Map.Entry;

public class SendTest implements Runnable{

    Map<InetAddress,Integer> map;
    String message;

    public SendTest(Map<InetAddress,Integer> map,String message){
        this.map=map;
        this.message=message;
    }


    @Override
    public void run() {
        try {
            DatagramSocket  ds=new DatagramSocket();
            byte[]b=message.getBytes();
            for(Entry<InetAddress, Integer> en:map.entrySet()){
                DatagramPacket dp=new DatagramPacket(b, b.length,en.getKey(),en.getValue());
                ds.send(dp);
            }
            ds.close();
        } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

        }
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章