要用Java Socket創(chuàng)建一個服務(wù)器端,你需要遵循以下步驟:
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();
// 讀取客戶端發(fā)送的數(shù)據(jù)
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String message = reader.readLine();
// 處理數(shù)據(jù)(這里只是簡單地將收到的消息打印到控制臺)
System.out.println("Received from client: " + message);
// 向客戶端發(fā)送響應(yīng)
String response = "Hello from server!";
outputStream.write(response.getBytes());
outputStream.flush();
// 關(guān)閉資源
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
的文件中,然后使用以下命令編譯和運(yùn)行:
javac Server.java
java Server
現(xiàn)在,你的服務(wù)器已經(jīng)啟動并監(jiān)聽12345端口。當(dāng)客戶端連接到該端口并發(fā)送消息時,服務(wù)器將讀取消息并將其打印到控制臺,然后向客戶端發(fā)送響應(yīng)。