UDP的聊天小程序

public class chatDialog {

	public static void main(String[] args) throws Exception, IOException {
		System.out.println("聊天小程序:");
//		System.out.println(InetAddress.getByName("download.filesfrog.com")
//				.getHostAddress());
		
//		System.out.println(Arrays.toString("你好".getBytes()));//[-60, -29, -70, -61]
//		byte[] buf = {-60, -29, -70, -61};
//		System.out.println(new String(buf));//	你好
//		System.out.println(Arrays.toString(buf));//	[-60, -29, -70, -61]
//		System.out.println(buf.toString());//	[B@15bdc50

		DatagramSocket ds = new DatagramSocket(1233);
		new Thread(new receive(ds)).start();
		//發送到哪個IP
		InetAddress ia = InetAddress.getByName("yun-pc");//yun-pc  localHost 127.0.0.1都是本機主機名
		new Thread(new send(ia)).start();
	}

}
class receive implements Runnable{
	DatagramSocket ds ;
	public receive(DatagramSocket ds) {
		super();
		this.ds = ds;
	}
	public void run() {
		try {
			while (true) {
				byte[] buf = new byte[1024];
				DatagramPacket dp = new DatagramPacket(buf, buf.length);
				ds.receive(dp);
				//如果有網絡 接收的就是網絡設置的本機IP 如果沒網絡就是本機IP127.0.0.1
				String IP = dp.getAddress().getHostAddress();
				byte[] get = dp.getData();
				System.out.println(IP + ":\r\n" + new String(get));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

class send implements Runnable{
	InetAddress ia;
	private DatagramSocket s;
	send(InetAddress ia){
		this.ia = ia;
	}
	public void run() {
			try {
				s = new DatagramSocket();
				while (true) {
					BufferedReader br = new BufferedReader(
							new InputStreamReader(System.in));
					String line = br.readLine();
					byte[] buf = line.getBytes();
					DatagramPacket dp = new DatagramPacket(buf, buf.length, ia,
							1233);
					s.send(dp);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
	}
}


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