我想从事Java后端开发,请给我一段代码示例
时间: 2023-04-09 17:03:33 浏览: 151
JAVA一个代码实例
当然,我可以给你一个 Java 后端开发的示例代码:
```java
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8080);
System.out.println("Server started on port 8080...");
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket.getInetAddress().getHostAddress());
Thread thread = new Thread(new ClientHandler(clientSocket));
thread.start();
}
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class ClientHandler implements Runnable {
private Socket clientSocket;
public ClientHandler(Socket clientSocket) {
this.clientSocket = clientSocket;
}
@Override
public void run() {
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("Received message from client: " + inputLine);
out.println("Server received message: " + inputLine);
}
in.close();
out.close();
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这是一个简单的 Java 后端服务器,它监听 8080 端口,接受客户端的连接,并在接收到客户端的消息后,将消息原样返回给客户端。当然,这只是一个示例代码,实际的 Java 后端开发需要更加复杂的代码和技术。
阅读全文