以下是一个简单的Java Socket编程实例,包括服务器端和客户端的代码。这个例子展示了如何创建一个服务器,该服务器监听一个端口,接受客户端连接,读取客户端发送的数据,并将数据回传给客户端。
服务器端代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleServer {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket clientSocket = null;
try {
// 创建服务器套接字
serverSocket = new ServerSocket(8080);
System.out.println("Server is listening on port 8080...");
// 接受客户端连接
clientSocket = serverSocket.accept();
System.out.println("Client connected.");
// 获取输入输出流
InputStream inputStream = clientSocket.getInputStream();
OutputStream outputStream = clientSocket.getOutputStream();
// 将输入流转换为BufferedReader以便读取
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
PrintWriter printWriter = new PrintWriter(outputStream, true);
// 读取客户端发送的数据
String message = bufferedReader.readLine();
System.out.println("Received from client: " + message);
// 将数据回传给客户端
printWriter.println("Echo: " + message);
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭套接字
try {
if (clientSocket != null) clientSocket.close();
if (serverSocket != null) serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
客户端代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
public class SimpleClient {
public static void main(String[] args) {
Socket socket = null;
try {
// 创建客户端套接字
socket = new Socket("localhost", 8080);
System.out.println("Connected to server.");
// 获取输入输出流
OutputStream outputStream = socket.getOutputStream();
PrintWriter printWriter = new PrintWriter(outputStream, true);
// 向服务器发送数据
printWriter.println("Hello, Server!");
// 读取服务器返回的数据
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String response = bufferedReader.readLine();
System.out.println("Server response: " + response);
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭套接字
try {
if (socket != null) socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
要运行这个例子,请首先启动服务器端代码,然后启动客户端代码。客户端将向服务器发送一条消息,服务器将读取该消息并将其回传给客户端。
请注意,这个例子仅用于教学目的,实际应用中可能需要考虑更多因素,如多线程处理并发连接、错误处理、安全性和性能优化等。