1. 程式人生 > >通過 UDP+多線程 實現聊天功能

通過 UDP+多線程 實現聊天功能

udp 多線程 聊天

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+":離開聊天室");

}

}

}

}


通過 UDP+多線程 實現聊天功能