Java进阶学习:网络服务器编程
Java进阶学习中,网络服务器编程是非常关键的一部分。本文将介绍网络服务器编程方面的完整攻略,包括必要的基础知识,如何创建网络服务器,如何创建服务器/客户端,以及一些实例说明。
1. 基础知识
在进行网络服务器编程之前,需要掌握以下基础知识:
- TCP/IP 协议
- Socket 编程
- 多线程编程
TCP/IP协议是 Internet 上数据通信的基础协议,Socket编程是实现网络通信的具体技术,多线程编程则是实现服务器的关键技术之一。
2. 创建网络服务器
创建网络服务器需要以下步骤:
- 创建一个ServerSocket实例,并指定端口号;
- 调用ServerSocket的accept()方法接收客户端请求,该方法将阻塞进程,直到有客户端请求连接;
- 将获得的Socket实例传递给一个新的线程进行处理,以允许服务器同时处理多个客户端的请求。
下面是一个简单的Java代码示例:
ServerSocket serverSocket = new ServerSocket(9999);
while (true) {
Socket socket = serverSocket.accept(); // 阻塞等待客户端连接请求
// 创建新线程处理客户端请求
Runnable runnable = new ServerThread(socket);
new Thread(runnable).start();
}
3. 创建服务器/客户端
创建服务器/客户端需要以下步骤:
- 创建一个ServerSocket实例,并指定端口号;
- 当服务器继续监听客户端请求时,创建一个Socket实例来连接到服务器;
- 通过Socket实例,向服务器发送请求或接收数据。
以下是一个Java代码示例:
// 服务器端
ServerSocket serverSocket = new ServerSocket(9999);
while (true) {
Socket socket = serverSocket.accept(); // 阻塞等待客户端连接请求
// 创建新线程处理客户端请求
Runnable runnable = new ServerThread(socket);
new Thread(runnable).start();
}
// 客户端
String host = "localhost";
int port = 9999;
Socket socket = new Socket(host, port);
// 发送请求
OutputStream outputStream = socket.getOutputStream();
outputStream.write("Hello, World!".getBytes());
// 接收响应
InputStream inputStream = socket.getInputStream();
byte[] bytes = new byte[1024];
int len = inputStream.read(bytes);
String response = new String(bytes, 0, len);
4. 实例说明
实例一
实现一个简单的聊天程序,允许多个客户端同时连接。当任何客户端发送消息时,服务器将消息广播给所有连接的客户端。
以下是Java代码示例:
// 服务器端
public class ChatServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("聊天室已开启,等待客户端接入...");
List<Socket> sockets = new ArrayList<>();
while (true) {
Socket socket = serverSocket.accept();
sockets.add(socket);
Runnable runnable = new ChatServerThread(socket, sockets);
new Thread(runnable).start();
}
}
}
public class ChatServerThread implements Runnable {
private Socket socket;
private List<Socket> sockets;
public ChatServerThread(Socket socket, List<Socket> sockets) {
this.socket = socket;
this.sockets = sockets;
}
@Override
public void run() {
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
String message = bufferedReader.readLine();
if (message == null) {
sockets.remove(socket);
break;
}
for (Socket socket : sockets) {
if (socket != this.socket) {
OutputStream outputStream = socket.getOutputStream();
outputStream.write(message.getBytes());
outputStream.flush();
}
}
}
System.out.println(socket.getRemoteSocketAddress() + " 已断连");
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 客户端
public class ChatClient {
public static void main(String[] args) throws IOException {
String host = "localhost";
int port = 9999;
Socket socket = new Socket(host, port);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
OutputStream outputStream = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
while (true) {
String message = bufferedReader.readLine();
outputStream.write(message.getBytes());
outputStream.flush();
byte[] bytes = new byte[1024];
int len = inputStream.read(bytes);
String response = new String(bytes, 0, len);
System.out.println("[" + socket.getInetAddress().getHostAddress() + "]:" + response);
}
}
}
实例二
实现一个简单的HTTP服务器,当服务器接收到HTTP请求时,返回一个HTML页面作为响应。
以下是Java代码示例:
public class HttpServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8080);
while (true) {
Socket socket = serverSocket.accept();
Runnable runnable = new HttpRequestThread(socket);
new Thread(runnable).start();
}
}
}
public class HttpRequestThread implements Runnable {
private Socket socket;
public HttpRequestThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
OutputStream outputStream = socket.getOutputStream();
PrintWriter printWriter = new PrintWriter(outputStream);
String line;
while ((line = bufferedReader.readLine()) != null && !line.equals("")) {
System.out.println(line);
}
String response = "<html><body><h1>Hello, World!</h1></body></html>";
printWriter.println("HTTP/1.1 200 OK");
printWriter.println("Content-Type: text/html");
printWriter.println("Content-Length: " + response.length());
printWriter.println("");
printWriter.println(response);
printWriter.flush();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 客户端
public class HttpClient {
public static void main(String[] args) throws IOException {
String host = "localhost";
int port = 8080;
Socket socket = new Socket(host, port);
OutputStream outputStream = socket.getOutputStream();
outputStream.write("GET / HTTP/1.1\r\nHost: localhost:8080\r\n\r\n".getBytes());
outputStream.flush();
InputStream inputStream = socket.getInputStream();
byte[] bytes = new byte[1024];
int len = inputStream.read(bytes);
String response = new String(bytes, 0, len);
System.out.println(response);
}
}
以上就是Java进阶学习中网络服务器编程方面的完整攻略,包括基础知识、创建网络服务器、创建服务器/客户端和实例说明。希望这篇文章能够对Java编程人员有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java进阶学习:网络服务器编程 - Python技术站