- package heima.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 UDPChatDemo {
- /**
- * @param 黑马程序员
- * -UDP聊天
- * @author 高一航
- */
- public static void main(String[] args) {
- try {
- DatagramSocket sendSocket = new DatagramSocket();
- DatagramSocket recieveSocket = new DatagramSocket(10001);//监听本机的10001端口
- new Thread(new Sender(sendSocket)).start();
- new Thread(new Receiver(recieveSocket)).start();
- } catch (SocketException e) {
- e.printStackTrace();
- }
- }
- }
- class Sender implements Runnable {
- private DatagramSocket ds;// 1,建立Socket端点
- private DatagramPacket dp;// 2,定义数据包,用于存储数据;
- public Sender(DatagramSocket ds) {
- this.ds = ds;
- }
- @Override
- public void run() {
- BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
- byte[] buf = new byte[1024];
- String line;
- try {
- while ((line = in.readLine()) != null) {
- buf = line.getBytes();
- dp = new DatagramPacket(buf, buf.length,
- InetAddress.getByName("127.0.0.1"), 10000);
- ds.send(dp);// 3,通过socket发送方法,将数据发送
- if ("bye".equalsIgnoreCase(line)) {
- break;
- }
- }
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- in.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- ds.close();
- System.out.println("sender resources closed");
- }
- }
- }
- class Receiver implements Runnable {
- private DatagramSocket ds;// 1,建立Socket端点
- public DatagramPacket dp;// 2,定义数据包,用于存储数据;
- public Receiver(DatagramSocket ds) {
- this.ds = ds;
- }
- @Override
- public void run() {
- byte[] buf = new byte[1024];
- String ip;
- String context;
- try {
- while (true) {
- dp = new DatagramPacket(buf, buf.length);
- ds.receive(dp);//3,通过socket的receive方法将数据存入数据包
- ip = dp.getAddress().getHostAddress();//获取IP
- context = new String(dp.getData(), 0, dp.getLength());//获取内容
- System.out.println(ip + " : " + context);
- }
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- ds.close();
- System.out.println("Receiver resources closed");
- }
- }
- }
复制代码 |