在Java中,Socket編程是一種實現客戶端和服務器之間通信的方式。以下是使用Java Socket進行數據傳輸的基本步驟:
首先,服務器端需要創建一個ServerSocket
對象來監聽指定的端口。
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
int port = 12345; // 監聽的端口號
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("服務器已啟動,正在監聽端口 " + port);
while (true) {
Socket clientSocket = serverSocket.accept(); // 接受客戶端連接
System.out.println("客戶端已連接: " + clientSocket.getInetAddress());
// 處理客戶端請求
handleClient(clientSocket);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void handleClient(Socket clientSocket) {
try (BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("收到客戶端消息: " + inputLine);
out.println("服務器已收到: " + inputLine);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
clientSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
客戶端需要創建一個Socket
對象來連接服務器。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
String hostname = "localhost"; // 服務器地址
int port = 12345; // 服務器端口號
try (Socket socket = new Socket(hostname, port)) {
System.out.println("已連接到服務器");
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String userInputLine;
while ((userInputLine = userInput.readLine()) != null) {
out.println(userInputLine); // 發送消息到服務器
String response = in.readLine(); // 接收服務器響應
System.out.println("服務器回復: " + response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Socket
對象的getInputStream()
方法獲取輸入流,讀取客戶端發送的數據;使用getOutputStream()
方法獲取輸出流,向客戶端發送數據。Socket
對象的getInputStream()
方法獲取輸入流,讀取服務器發送的數據;使用getOutputStream()
方法獲取輸出流,向服務器發送數據。在數據傳輸完成后,應該關閉所有的流和Socket連接。
try {
in.close();
out.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
通過以上步驟,你就可以使用Java Socket進行基本的數據傳輸了。根據具體需求,可以進一步擴展和優化代碼。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。