?? serverudp.java.bak
字號:
import java.io.*;
import java.net.*;
import java.util.*;
/**類ServerDatagram是數(shù)據(jù)報通信的服務(wù)器端程序,該程序用于實現(xiàn):
當有一個客戶端連接到端口上時,就新建一個線程,該線程讀取當前
路徑下thirdFile.txt文件中的內(nèi)容,每次讀取一行,將讀取的內(nèi)容
通過數(shù)據(jù)報傳送到客戶端并在客戶端顯示出來*/
public class ServerUDP{
public static void main(String[] args){
try{
/*生成一個ServerDataThread類的對象,在ServerDataThread類中實現(xiàn)了數(shù)據(jù)報通信的服務(wù)器端處理*/
ServerDataThread threadObj = new ServerDataThread();
/*ServerDataThread類是Thread類的子類,因此threadObj也是一個線程對象*/
threadObj.start();
}catch(IOException e){}
}
}
/**ServerDataThread類是Thread類的子類,用于進行數(shù)據(jù)報通信*/
class ServerDataThread extends Thread{
/*聲明一個DatagramSocket對象,初始值為null,用于數(shù)據(jù)報的接收和發(fā)送*/
protected DatagramSocket socketObj = null;
/*聲明一個BufferedReader類的對象,初值為null,用于創(chuàng)建一個輸入流*/
protected BufferedReader buffObj = null;
/*聲明一個布爾變量existData,用于判斷輸入流中是否還有數(shù)據(jù)*/
protected boolean existData = true;
/**構(gòu)造方法ServerDataThread()實例化DatagramSocket對象,并創(chuàng)建輸入流*/
public ServerDataThread() throws IOException{
/*進行文件例外處理,因為有可能文件不存在*/
try{
/*聲明一個FileReader對象,這樣服務(wù)器端就可以對當前路徑下的thirdFile.txt文件進行讀取操作*/
FileReader fileObj = new FileReader("thirdFile.txt");
/*實例化BufferedReader對象,以提供文件讀取的效率*/
buffObj = new BufferedReader(fileObj);
}catch(FileNotFoundException e){
System.err.println("文件對象不存在");
}
}
/**方法run()實現(xiàn)數(shù)據(jù)報通信*/
public void run(){
/*while循環(huán)用于判斷當前文件流中是否還存在數(shù)據(jù)*/
while(existData)
{
try{
/*聲明一個byte類型的數(shù)組buf,用于存放數(shù)據(jù)報中的數(shù)據(jù)*/
byte[] buf=new byte[256];
/*聲明一個字符串變量tempStr*/
String tempStr = "";
/*聲明一個字符串變量totalStr,用于存儲文件內(nèi)容*/
String totalStr = "";
socketObj = new DatagramSocket();
/*根據(jù)文件流對象是否存在進行不同的處理*/
if(buffObj == null)//文件對象不存在
tempStr = "This file Object doesn't exist!";
else//文件對象存在
{
try{
/*while循環(huán)語句獲得文件中的內(nèi)容*/
while((tempStr = buffObj.readLine())!=null)
{
totalStr += tempStr+"\n";
}
/*沒有數(shù)據(jù)時,就將文件流關(guān)閉*/
buffObj.close();
/*將布爾變量賦值為false*/
existData = false;
/*給字符串變量賦值,表示文件流到達結(jié)尾處*/
tempStr = "No more data in file.This is the end";
}catch(IOException e){
tempStr = "IOException occurred in server.";
}
}
/*將字符串轉(zhuǎn)換成byte型*/
buf = totalStr.getBytes();
/*設(shè)置數(shù)據(jù)報對應(yīng)的IP地址,這里是本機地址*/
InetAddress ipAddress=InetAddress.getByName("127.0.0.1");
/*獲得數(shù)據(jù)報的端口號*/
int portObj=3325;
/*重新實例化DatagramPacket對象,用于發(fā)送數(shù)據(jù)報*/
DatagramPacket packetObj=new DatagramPacket(buf,buf.length,ipAddress,portObj);
/*發(fā)送數(shù)據(jù)報*/
socketObj.send(packetObj);
}catch(IOException e){
/*如果出現(xiàn)例外,對例外進行跟蹤,并輸出跟蹤信息*/
e.printStackTrace();
/*出現(xiàn)例外,將布爾變量existData置為false,以控制while循環(huán)*/
existData = false;
}
}
/*將數(shù)據(jù)報關(guān)閉*/
socketObj.close();
}
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -