package liu.net.udp;


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;


import javax.swing.plaf.synth.SynthSpinnerUI;


public class ChatUseUdp {

public static void main(String[] args) throws SocketException {

//通过   UDP+多线程  实现聊天功能

//通过UDP协议完成一个聊天程序。一个负责发送数据的任务。一个负责接收数据的任务。两个任务需要同时进行,用多线程技术

//创建socket服务

DatagramSocket send = new DatagramSocket(10006);

//此端口需要与发送端指定的端口一致,否则接收不到数据

DatagramSocket rece = new DatagramSocket(10007);

new Thread(new Send(send)).start();

new Thread(new Receive(rece)).start();

}


}


//实现发送数据的类

class Send implements Runnable {

private DatagramSocket ds;

public Send(DatagramSocket ds) {

super();

this.ds = ds;

}


public void run() {

//具体要发送数据的内容

//1.从键盘输入发送的数据

BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

//读取数据

String line = null;

try{

while((line=bf.readLine())!=null){

//2.将数据封装到数据包中

byte[] buf = line.getBytes();

DatagramPacket dp = new DatagramPacket(buf,buf.length,

InetAddress.getByName("127.0.0.1"),10007);

//3.把数据发送出去

ds.send(dp);

if("over".equals(line)){

break;

}

}

ds.close();

}catch(IOException e){

e.printStackTrace();

}

}

}





//实现接收数据的类

class Receive implements Runnable {

private DatagramSocket ds;

public Receive(DatagramSocket ds) {

super();

this.ds = ds;

}


public void run() {

while(true){

//接收的具体任务内容

//1.因为接收的数据最终都会存储到数据包中,而数据包中必须有字节数组

byte[] buf = new byte[1024];

//2.创建数据包对象

DatagramPacket dp = new DatagramPacket(buf,buf.length);

//3.将收到的数据存储到数据包中

try {

ds.receive(dp);

} catch (IOException e) {

e.printStackTrace();

}

//4.获取数据

String ip = dp.getAddress().getHostAddress();

String data = new String(dp.getData(),0,dp.getLength());

System.out.println(ip+":"+data);

if("over".equals(data)){

System.out.println(ip+":离开聊天室");

}

}

}

}