首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 編程那些事兒 108:網絡編程示例一——質數判斷(TCP/UDP 雙版本)

     編輯:Java 相關知識

13.3 網絡編程示例

「實踐出真知」,透過兩個簡單示例演示實際使用。

13.3.1 質數判別示例

功能:客戶端接收用戶輸入數字 → 發送至服務端 → 服務端判斷質數 → 回饋結果 → 客戶端顯示。質數規則:最小質數 2,僅能被 1 和自身整除的自然數。輸入 <2 或非自然數視為非法。

功能分解

客戶端:接收輸入、校驗合法性、按協議生成發送數據、發送、接收回饋、解析輸出。
服務端:接收數據、解析協議、判斷質數、生成回饋協議數據、發送回饋。

協議設計

客戶端發送:數字轉字符串再轉 byte 陣列(如輸入 16 → "16" → getBytes())。發送 "quit" 結束連接。
服務端回饋:1 字節,0=質數、1=非質數、2=協議格式錯誤(如發送 12 回 1、13 回 0、0 回 2)。

TCP 版客戶端代碼

package example1;
import java.io.*;
import java.net.*;

public class TCPPrimeClient {
static BufferedReader br;
static Socket socket;
static InputStream is;
static OutputStream os;
final static String HOST = "127.0.0.1";
final static int PORT = 10005;

public static void main(String[] args) {
init();
while (true) {
System.out.println("請輸入數字:");
String input = readInput();
if (isQuit(input)) { send("quit".getBytes()); break; }
if (checkInput(input)) {
send(input.getBytes());
byte[] data = receive();
parse(data);
} else {
System.out.println("輸入不合法,請重新輸入!");
}
}
close();
}

private static void init() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
socket = new Socket(HOST, PORT);
is = socket.getInputStream();
os = socket.getOutputStream();
} catch (Exception e) {}
}

private static String readInput() {
try { return br.readLine(); } catch (Exception e) { return null; }
}

private static boolean isQuit(String input) {
if (input == null) return false;
return "quit".equalsIgnoreCase(input);
}

private static boolean checkInput(String input) {
if (input == null) return false;
try {
int n = Integer.parseInt(input);
return n >= 2;
} catch (Exception e) { return false; }
}

private static void send(byte[] data) {
try { os.write(data); } catch (Exception e) {}
}

private static byte[] receive() {
byte[] b = new byte[1024];
try {
int n = is.read(b);
byte[] data = new byte[n];
System.arraycopy(b, 0, data, 0, n);
return data;
} catch (Exception e) { return null; }
}

private static void parse(byte[] data) {
if (data == null) { System.out.println("服務器端回饋數據不正確!"); return; }
byte value = data[0];
switch (value) {
case 0: System.out.println("質數"); break;
case 1: System.out.println("不是質數"); break;
case 2: System.out.println("協議格式錯誤"); break;
}
}

private static void close() {
try { br.close(); is.close(); os.close(); socket.close(); } catch (Exception e) { e.printStackTrace(); }
}
}

代碼以方法組織功能,結構清晰,主邏輯在 main 方法。

TCP 版服務端代碼

package example1;
import java.net.*;

public class TCPPrimeServer {
public static void main(String[] args) {
final int PORT = 10005;
ServerSocket ss = null;
try {
ss = new ServerSocket(PORT);
System.out.println("服務器端已啟動:");
while (true) {
Socket s = ss.accept();
new PrimeLogicThread(s);
}
} catch (Exception e) {}
finally {
try { ss.close(); } catch (Exception e2) {}
}
}
}

package example1;
import java.io.*;
import java.net.*;

public class PrimeLogicThread extends Thread {
Socket socket;
InputStream is;
OutputStream os;

public PrimeLogicThread(Socket socket) {
this.socket = socket;
init();
start();
}

private void init() {
try { is = socket.getInputStream(); os = socket.getOutputStream(); } catch (Exception e) {}
}

public void run() {
while (true) {
byte[] data = receive();
if (isQuit(data)) break;
byte[] b = logic(data);
send(b);
}
close();
}

private byte[] receive() {
byte[] b = new byte[1024];
try {
int n = is.read(b);
byte[] data = new byte[n];
System.arraycopy(b, 0, data, 0, n);
return data;
} catch (Exception e) { return null; }
}

private void send(byte[] data) {
try { os.write(data); } catch (Exception e) {}
}

private boolean isQuit(byte[] data) {
if (data == null) return false;
String s = new String(data);
return "quit".equalsIgnoreCase(s);
}

private byte[] logic(byte[] data) {
byte[] b = new byte[1];
if (data == null) { b[0] = 2; return b; }
try {
String s = new String(data);
int n = Integer.parseInt(s);
if (n >= 2) {
boolean flag = isPrime(n);
b[0] = flag ? 0 : 1;
} else {
b[0] = 2;
System.out.println(n);
}
} catch (Exception e) { e.printStackTrace(); b[0] = 2; }
return b;
}

private boolean isPrime(int n) {
for (int i = 2; i <= Math.sqrt(n); i++)
if (n % i == 0) return false;
return true;
}

private void close() {
try { is.close(); os.close(); socket.close(); } catch (Exception e) {}
}
}

服務端結構一致,邏輯線程中 logic 方法實現質數判斷並按協議生成回饋。UDP 版本實現類似,注意差異。客戶端均可多次輸入,UDP 無需發送 "quit"。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved