在Java中,建立Socket連接主要包括兩個步驟:服務(wù)器端創(chuàng)建ServerSocket對象并監(jiān)聽指定端口,客戶端創(chuàng)建Socket對象并連接到服務(wù)器的IP地址和端口。以下是一個簡單的示例:
服務(wù)器端代碼:
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
int port = 12345; // 服務(wù)器監(jiān)聽的端口號
ServerSocket serverSocket = new ServerSocket(port); // 創(chuàng)建ServerSocket對象
System.out.println("服務(wù)器已啟動,正在監(jiān)聽端口:" + port);
Socket socket = serverSocket.accept(); // 等待客戶端連接
System.out.println("客戶端已連接:" + socket.getInetAddress());
InputStream inputStream = socket.getInputStream(); // 獲取客戶端發(fā)送的數(shù)據(jù)流
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String message;
while ((message = bufferedReader.readLine()) != null) {
System.out.println("收到客戶端消息:" + message);
}
socket.close(); // 關(guān)閉Socket連接
serverSocket.close(); // 關(guān)閉ServerSocket對象
}
}
客戶端代碼:
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
String serverAddress = "localhost"; // 服務(wù)器IP地址
int port = 12345; // 服務(wù)器監(jiān)聽的端口號
Socket socket = new Socket(serverAddress, port); // 創(chuàng)建Socket對象并連接到服務(wù)器
System.out.println("已連接到服務(wù)器:" + serverAddress + ":" + port);
OutputStream outputStream = socket.getOutputStream(); // 獲取服務(wù)器發(fā)送的數(shù)據(jù)流
PrintWriter printWriter = new PrintWriter(outputStream, true);
String message = "你好,服務(wù)器!";
printWriter.println(message); // 向服務(wù)器發(fā)送消息
System.out.println("已發(fā)送消息:" + message);
socket.close(); // 關(guān)閉Socket連接
}
}
在這個示例中,服務(wù)器端創(chuàng)建了一個ServerSocket對象并監(jiān)聽12345端口。當(dāng)客戶端連接到服務(wù)器時,服務(wù)器會接收到客戶端的消息并在控制臺輸出。客戶端創(chuàng)建一個Socket對象并連接到服務(wù)器的IP地址和端口,然后向服務(wù)器發(fā)送一條消息。