简单群聊代码

package com.zyf.day23;

public class ChatMain {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
        ChatReceive chatReceive = new ChatReceive();
        chatReceive.start();
        
        ChatSender chatSender = new ChatSender();
        chatSender.start();
	}

}

package com.zyf.day23;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class ChatReceive extends Thread{

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub

		try {
			//建立udp的服务,要监听一个端口
			DatagramSocket socket;
			socket = new DatagramSocket(9090);
			byte[] buf = new byte[1024];
			int length = 0;
			DatagramPacket packet = new DatagramPacket(buf,buf.length);
			while(true){
				socket.receive(packet);
				//packet.getAddress() 获取对方数据包的IP地址对象
				System.out.println(packet.getAddress().getHostAddress() + "say:" + new String(buf,0,packet.getLength()));
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}

package com.zyf.day23;

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 ChatSender extends Thread {
    @Override
    public void run() {
    	try{
    	 	// TODO Auto-generated method stub
        	//建立udp的服务
        	DatagramSocket socket = new DatagramSocket();
        	//准备数据,把数据封装到数据包中发送
        	BufferedReader keyReader = new BufferedReader(new InputStreamReader(System.in));
        	String line = null;
        	DatagramPacket packet = null;
        	while((line = keyReader.readLine()) != null){
        		packet = new DatagramPacket(line.getBytes(),line.getBytes().length,InetAddress.getByName("192.168.1.199"),9090);
        		socket.send(packet);
        	}
        	socket.close();
    	}catch(IOException e){
    		e.printStackTrace();
    	}
   
    }
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}

你可能感兴趣的:(java)