\n (單行文本)
public class JavaServer {
public static void main(String[] args) throws IOException {
try (ServerSocket server = new ServerSocket(8888)) {
System.out.println("Java Server listening on 8888...");
while (true) {
Socket client = server.accept();
new Thread(() -> handle(client)).start();
}
}
}
static void handle(Socket socket) {
try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8), true)) {
String line;
while ((line = in.readLine()) != null) { // 讀取以 \n 結尾的行
System.out.println("Recv from C#: " + line);
// 回覆
out.println("Java Echo: " + line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class CSharpClient {
public static void Main() {
using (TcpClient client = new TcpClient("127.0.0.1", 8888))
using (NetworkStream stream = client.GetStream())
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8) { AutoFlush = true }) {
// 發送
writer.WriteLine("Hello from C#");
// 接收
string reply = reader.ReadLine();
Console.WriteLine("Recv from Java: " + reply);
// 持續互動
while (true) {
Console.Write("> ");
string input = Console.ReadLine();
if (input == "exit") break;
writer.WriteLine(input);
Console.WriteLine("Server: " + reader.ReadLine());
}
}
}
}
| 問題 | Java 處理 | C# 處理 |
|---|---|---|
| 編碼不一致 | StandardCharsets.UTF_8 | Encoding.UTF8 |
| 訊息邊界 | readLine() / println() 自動處理 \n | ReadLine() / WriteLine() |
| 緩衝區未刷新 | PrintWriter(..., true) 自動 flush | AutoFlush = true |
| 半包/黏包 | 行協議天然解決 (單行業務) | 同左 |
| 異常斷開 | readLine() == null 檢測 | ReadLine() == null |
若需傳輸 JSON/Protobuf 等二進制資料,改用「長度前綴 (4 bytes) + Payload」協議,雙端用 DataInputStream/BinaryReader 讀寫。