在Java中,Socket數據傳輸主要涉及到兩個類:java.net.Socket
(用于客戶端)和java.net.ServerSocket
(用于服務器端)。以下是一個簡單的示例,展示了如何使用這兩個類進行數據傳輸。
服務器端
accept()
方法,等待客戶端連接。accept()
方法返回一個新的Socket對象,用于與客戶端進行通信。getInputStream()
)和輸出流(getOutputStream()
)進行數據讀寫。客戶端
getInputStream()
)和輸出流(getOutputStream()
)進行數據讀寫。以下是一個簡單的Java Socket數據傳輸示例:
服務器端代碼
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
int port = 12345;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server is listening on port " + port);
Socket socket = serverSocket.accept();
System.out.println("Client connected");
InputStream inputStream = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String message = reader.readLine();
System.out.println("Received message: " + message);
OutputStream outputStream = socket.getOutputStream();
PrintWriter writer = new PrintWriter(outputStream, true);
writer.println("Hello from server");
socket.close();
serverSocket.close();
}
}
客戶端代碼
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
String serverAddress = "localhost";
int port = 12345;
Socket socket = new Socket(serverAddress, port);
System.out.println("Connected to server");
OutputStream outputStream = socket.getOutputStream();
PrintWriter writer = new PrintWriter(outputStream, true);
writer.println("Hello from client");
InputStream inputStream = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String message = reader.readLine();
System.out.println("Received message: " + message);
socket.close();
}
}
在這個示例中,服務器監聽端口12345,并在接收到客戶端連接后,與客戶端進行數據交換。客戶端連接到服務器并發送一條消息,然后服務器回復一條消息。最后,雙方都關閉了Socket連接。