package liu.net.udp;java
import java.io.BufferedReader;數組
import java.io.IOException;多線程
import java.io.InputStreamReader;socket
import java.net.DatagramPacket;ide
import java.net.DatagramSocket;this
import java.net.InetAddress;spa
import java.net.SocketException;.net
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+":離開聊天室");
}
}
}
}