java UDP聊天

package com.net;

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

public class ChatUdpDemo {

	public static void main(String[] args) {
		try {
			DatagramSocket sendds = new DatagramSocket();
			DatagramSocket receds = new DatagramSocket(10000);
			new Thread(new Send(sendds)).start();
			new Thread(new Rece(receds)).start();
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}

}

class Send implements Runnable {
	private DatagramSocket ds = null;

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

	@Override
	public void run() {
		DatagramPacket dp = null;
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		try {
			for (String line; (line = br.readLine()) != null;) {
				if ("byebye".equals(line))
					break;
				byte[] buf = line.getBytes();
				dp = new DatagramPacket(buf, buf.length,
						InetAddress.getByName("127.0.0.1"), 10000);
				ds.send(dp);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

class Rece implements Runnable {

	private DatagramSocket ds = null;

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

	@Override
	public void run() {
		DatagramPacket dp = null;
		byte[] buf = new byte[1024 * 64];
		dp = new DatagramPacket(buf, buf.length);
		try {
			while (true) {
				ds.receive(dp);
				System.out.println("ip=" + dp.getAddress().getHostAddress() + "port=" + dp.getPort() + "say" + new String(dp.getData(),0,dp.getLength()));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

你可能感兴趣的:(自己用)