用Java语言编写简单聊天程序

Tips:编写一个聊天程序。传输层使用UDP协议。可以同时接收、发送数据 需要多线程技术一个线程控制接收,一个线程发送 因为收和发动作不一致,定义两个run方法这两个方法封装在不同的类中	 
 
  
import java.io.*;
import java.net.*;
/*
 * 创建局域网聊天
 */
public class UDPChat{
	public static void main(String[] arr) throws Exception{
		DatagramSocket sendsocket = new DatagramSocket();
		DatagramSocket recesocket = new DatagramSocket(10239);
		
		new Thread(new UDPSendChat(sendsocket)).start();
		new Thread(new UDPReceChat(recesocket)).start();
	}
}

class UDPSendChat implements Runnable {
	
	private DatagramSocket ds;
	public UDPSendChat(DatagramSocket ds) {
		this.ds = ds;
	}
	@Override
	public void run() {
	try {
		BufferedReader br = new 
				BufferedReader(new InputStreamReader(System.in));
		
		String line = null;
		
		while((line = br.readLine())!=null){//read阻塞式方法
			
			if("886".equals(line))
				break;
			
			byte[] buf = line.getBytes();
			
			DatagramPacket dp = new 
					DatagramPacket(buf, buf.length, InetAddress.getLocalHost(), 10239);
			
			ds.send(dp);
		}
	} catch (Exception e) {
		throw new RuntimeException("发送失败");
	}
		
	}

 	
}

class UDPReceChat implements Runnable {

	private DatagramSocket ds;
	public UDPReceChat(DatagramSocket ds) {
		this.ds = ds;
	}

	@Override
	public void run() {
		try {
			while(true){

				byte[] buf = new byte[1024];
				DatagramPacket dp = new DatagramPacket(buf, buf.length);
					
				ds.receive(dp);//阻塞式方法
				
				String ip = dp.getAddress().getHostAddress();
				String data = new String(dp.getData(),0,dp.getLength());
		        System.out.println(ip+"..."+data);  
				   }
		} catch (Exception e) {
			throw new RuntimeException("接受失败");
		}
		
	}

}
不同的IP地址上聊天截图:




你可能感兴趣的:(Java)