【JavaEE初阶】 网络编程基础与Socket套接字
在Java中,网络编程基于java.net
包,其中最常用的是Socket
类和ServerSocket
类。
ServerSocket示例代码:
import java.io.*;
import java.net.*;
public class SimpleServer {
public static void main(String[] args) throws IOException {
int port = 1234; // 选择一个端口
try (ServerSocket serverSocket = new ServerSocket(port);
Socket clientSocket = serverSocket.accept(); // 等待客户端连接
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))) {
String message = "Hello from server!";
writer.println(message); // 发送消息给客户端
String response = reader.readLine(); // 读取客户端的响应
System.out.println("Client says: " + response);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Socket示例代码:
import java.io.*;
import java.net.*;
public class SimpleClient {
public static void main(String[] args) throws IOException {
String host = "localhost"; // 服务器地址
int port = 1234; // 服务器端口
try (Socket socket = new Socket(host, port);
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
String response = reader.readLine(); // 读取服务器的消息
System.out.println("Server says: " + response);
String message = "Hello from client!";
writer.println(message); // 发送消息给服务器
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + host);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " + host);
}
}
}
以上代码展示了如何创建一个简单的服务器和客户端。服务器在特定端口上监听,客户端连接到服务器,然后双方通过PrintWriter
和BufferedReader
发送和接收文本消息。这是网络编程的基础,对于初学者来说,理解这些代码对于后续的网络编程学习非常重要。
评论已关闭