【Java Tutorial-package】mygame類的實現分析
阿新 • • 發佈:2018-12-13
包裹名 | 類名 |
---|---|
mygame server | server |
mygame client | client |
mygame shared | Utilities |
每一個類的實現: 首先是share,用於傳遞資訊和放置公用——
package mygame.shared;
public class Utilities {
// set DEBUG = false and compile to stop debug messages
final static boolean DEBUG = true;
public static void printMsg(String msg) {
if (DEBUG) {
System.out.println(msg);
}
}
}
接下來是客戶端
package mygame.client;//首先要聲名一個包
import java.io.*;
import java.net.*;
import java.util.*;
import mygame.shared.Utilities;
public class Client extends Thread {
Socket clientSocket = null;
/*thread類與runnable等程序執行緒操作相關
socket套接字用於實現client與其他類之間的通訊與資料傳遞
此處聲名了一個socket為clientSocket*/
public Client(Socket s) {
clientSocket = s;//實現賦值的方法
}
public void run() {
if (clientSocket == null) {
return;
}
PrintStream out = null;//定義輸出流為空
Utilities.printMsg("creating output stream");//輸出這句話
try {
out = new PrintStream(clientSocket.getOutputStream());
/*定義輸出流為getOut的套接字輸出流*/
} catch (IOException e) {
System.err.println("Error binding output to socket, " + e);
System.exit(1);
}//用try+catch結構輸出異常並跳出
Utilities.printMsg("writing current date");
Date d = new Date();
/*newdate也不一定是隻能輸出當年當月當日的本機時間
可以直接使用 Date date = new Date(2016-1900,8-1,28);
並且用systemoutp來輸出,但是要注意在年份上減去1900;
或者使用Calendar物件加以構造
Calendar c1 = Calendar.getInstance();
c1.set(2016,8-1,28);*/
out.println(d);
try {
out.close();
clientSocket.close();//關閉套接字
} catch (IOException e) {
}
}
protected void finalize() {
if (clientSocket != null) {
try {
clientSocket.close();
} catch (IOException e) {
}
clientSocket = null;
}
} //finalize個人覺得用處不大
}
最後是server部分
package mygame.server;
import java.io.*;
import java.net.*;
import mygame.client.Client;
import mygame.shared.Utilities;
//由於已經有了client與utilities兩個類,需要把介面都放進來
public class Server {
public static void main(String args[]) {
ServerSocket serverSocket = null;//同樣聲名一個套接字
Utilities.printMsg("creating server socket");
try {
serverSocket = new ServerSocket(4444);//佔用介面4444
} catch (IOException e) {
System.err.println("Unable to create server socket, " + e);
System.exit(1);
}
Utilities.printMsg("accepting client connections");
while (true) {
try {
Socket clientSocket = serverSocket.accept();//接受連線請求
new Client(clientSocket).start();
} catch (IOException e) {
System.err.println("Unable to accept socket connection, " + e);
System.exit(1);//報錯並輸出
}
}
}
}