要用Java Socket創建一個服務器端,你需要遵循以下步驟:
import java.io.*;
import java.net.*;
int port = 12345;
ServerSocket serverSocket = new ServerSocket(port);
while (true) {
// 接受客戶端連接
Socket clientSocket = serverSocket.accept();
// 處理客戶端請求
handleClient(clientSocket);
}
private void handleClient(Socket clientSocket) {
try {
// 獲取輸入輸出流
InputStream inputStream = clientSocket.getInputStream();
OutputStream outputStream = clientSocket.getOutputStream();
// 讀取客戶端發送的數據
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String message = reader.readLine();
// 處理數據(這里只是簡單地將收到的消息打印到控制臺)
System.out.println("Received from client: " + message);
// 向客戶端發送響應
String response = "Hello from server!";
outputStream.write(response.getBytes());
outputStream.flush();
// 關閉資源
reader.close();
outputStream.close();
clientSocket.close();
} catch (IOException e) {
System.out.println("Error handling client: " + e.getMessage());
}
}
public static void main(String[] args) {
int port = 12345;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server started on port " + port);
while (true) {
// 接受客戶端連接
Socket clientSocket = serverSocket.accept();
// 處理客戶端請求
handleClient(clientSocket);
}
}
將以上代碼保存到一個名為Server.java
的文件中,然后使用以下命令編譯和運行:
javac Server.java
java Server
現在,你的服務器已經啟動并監聽12345端口。當客戶端連接到該端口并發送消息時,服務器將讀取消息并將其打印到控制臺,然后向客戶端發送響應。