通過該UserInfo類的封裝
程序清單
//聊天交換信息的工具類
public class ComUtil
{
//使用常量作為本程序的多點廣播IP地址
private static final String BROADCAST_IP
=
//使用常量作為本程序的多點廣播目的的端口
//DatagramSocket所用的的端口為該端口
public static final int BROADCAST_PORT =
//定義每個數據報的最大大小為
private static final int DATA_LEN =
//定義本程序的MulticastSocket實例
private MulticastSocket socket = null;
//定義本程序私聊的Socket實例
private DatagramSocket singleSocket = null;
//定義廣播的IP地址
private InetAddress broadcastAddress = null;
//定義接收網絡數據的字節數組
byte[] inBuff = new byte[DATA_LEN];
//以指定字節數組創建准備接受數據的DatagramPacket對象
private DatagramPacket inPacket =
new DatagramPacket(inBuff
//定義一個用於發送的DatagramPacket對象
private DatagramPacket outPacket = null;
//聊天的主界面
private LanChat lanTalk;
//構造器
public ComUtil(LanChat lanTalk)throws IOException
{
this
//創建用於發送
//因為該MulticastSocket對象需要接收
socket = new MulticastSocket(BROADCAST_PORT)
//創建私聊用的DatagramSocket對象
singleSocket = new DatagramSocket(BROADCAST_PORT +
broadcastAddress = InetAddress
//將該socket加入指定的多點廣播地址
socket
//設置本MulticastSocket發送的數據報被回送到自身
socket
//初始化發送用的DatagramSocket
outPacket = new DatagramPacket(new byte[
broadcastAddress
//啟動兩個讀取網絡數據的線程
new ReadBroad()
Thread
new ReadSingle()
}
//廣播消息的工具方法
public void broadCast(String msg)
{
try
{
//將msg字符串轉換字節數組
byte[] buff = msg
//設置發送用的DatagramPacket裡的字節數據
outPacket
//發送數據報
socket
}
//捕捉異常
catch (IOException ex)
{
ex
if (socket != null)
{
//關閉該Socket對象
socket
}
JOptionPane
System
}
}
//定義向單獨用戶發送消息的方法
public void sendSingle(String msg
{
try
{
//將msg字符串轉換字節數組
byte[] buff = msg
DatagramPacket packet = new DatagramPacket(
buff
singleSocket
}
//捕捉異常
catch (IOException ex)
{
ex
if (singleSocket != null)
{
//關閉該Socket對象
singleSocket
}
JOptionPane
System
}
}
//不斷從DatagramSocket中讀取數據的線程
class ReadSingle extends Thread
{
//定義接收網絡數據的字節數組
byte[] singleBuff = new byte[DATA_LEN];
private DatagramPacket singlePacket =
new DatagramPacket(singleBuff
public void run()
{
while (true)
{
try
{
//讀取Socket中的數據
singleSocket
//處理讀到的信息
lanTalk
}
//捕捉異常
catch (IOException ex)
{
ex
if (singleSocket != null)
{
//關閉該Socket對象
singleSocket
}
JOptionPane
System
}
}
}
}
//持續讀取MulticastSocket的線程
class ReadBroad extends Thread
{
public void run()
{
while (true)
{
try
{
//讀取Socket中的數據
socket
//打印輸出從socket中讀取的內容
String msg = new String(inBuff
//讀到的內容是在線信息
if (msg
&& msg
{
String userMsg = msg
String[] userInfo = userMsg
UserInfo user = new UserInfo(userInfo[
inPacket
//控制是否需要添加該用戶的旗標
boolean addFlag = true;
ArrayList<Integer> delList = new ArrayList<Integer>()
//遍歷系統中已有的所有用戶
for (int i =
{
UserInfo current = lanTalk
//將所有用戶失去聯系的次數加
current
//如果該信息由指定用戶發送過來
if (current
{
current
//設置該用戶無須添加
addFlag = false;
}
if (current
{
delList
}
}
//刪除delList中的所有索引對應的用戶
for (int i =
{
lanTalk
}
if (addFlag)
{
//添加新用戶
lanTalk
}
}
//讀到的內容是公聊信息
else
{
//處理讀到的信息
lanTalk
}
}
//捕捉異常
catch (IOException ex)
{
ex
if (socket != null)
{
//關閉該Socket對象
socket
}
JOptionPane
System
}
}
}
}
}
返回目錄
編輯推薦
Java程序性能優化
新手學Java
Java程序設計培訓視頻教程
From:http://tw.wingwit.com/Article/program/Java/hx/201311/27256.html