用ServiceSocketChannel 写个服务端,发送消息给客户端
时间: 2024-10-25 18:13:05 浏览: 8
在Java中,你可以使用`java.nio.channels.SocketChannel`和`java.net.ServerSocketChannel`创建一个基于TCP的服务端,用于接收客户端的消息并发送回复。以下是简单的示例代码:
```java
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
public class SimpleServer {
private static final int PORT = 9000;
private Selector selector;
private ServerSocketChannel serverSocket;
public static void main(String[] args) {
new SimpleServer().start();
}
public void start() {
try {
// 创建服务器套接字通道
serverSocket = ServerSocketChannel.open();
serverSocket.configureBlocking(false);
serverSocket.socket().bind(new InetSocketAddress(PORT));
// 初始化Selector
selector = Selector.open();
// 注册监听连接请求事件
serverSocket.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("Server started on port " + PORT);
while (true) {
// 选择可用的键
selector.select();
for (SelectionKey key : selector.selectedKeys()) {
if (key.isAcceptable()) { // 接受新连接
acceptConnection(key);
} else if (key.isReadable()) { // 客户端发送数据
handleRead(key);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void acceptConnection(SelectionKey key) throws IOException {
ServerSocketChannel server = (ServerSocketChannel) key.channel();
SocketChannel client = server.accept(); // 接收连接
client.configureBlocking(false); // 非阻塞模式
// 绑定新的键到客户端通道,处理读取和写入
client.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
}
private void handleRead(SelectionKey key) throws IOException {
SocketChannel client = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(4096); // 缓冲区大小
int bytesReceived = client.read(buffer); // 读取数据
if (bytesReceived > 0) {
buffer.flip(); // 将缓冲区翻转以便读取数据
String message = new String(buffer.array(), 0, bytesReceived); // 转换为字符串
// 在这里处理收到的消息,例如打印或转发给其他服务
System.out.println("Received from client: " + message);
// 回应客户端,可以构造一个类似"ACK: " + message 的响应
sendResponse(client, "ACK: " + message);
} else if (bytesReceived == -1) { // 关闭连接
client.close();
key.cancel();
} else {
// 如果读取失败,取消选键
key.cancel();
}
}
private void sendResponse(SocketChannel client, String response) throws IOException {
client.write(ByteBuffer.wrap(response.getBytes()));
}
}
```
这个例子展示了如何创建一个简单的服务端,它会等待客户端连接,接收客户端发来的消息,并回送确认信息。记得在实际应用中添加错误处理和适当的数据包装。
阅读全文