1. 声明
当前内容主要为记录和学习使用Vert.x创建Tcp服务并实现通信的demo,当前内容参考官方文档
2. Server Demo
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.impl.BufferImpl;
public class TcpServer extends AbstractVerticle {
@Override
public void start(Promise<Void> startPromise) throws Exception {
vertx.createNetServer().connectHandler(socket -> {
socket.handler(buffer -> {
String context = buffer.toString("utf-8");
System.out.println("server received some bytes: " + buffer.length()+",context :"+context);
BufferImpl bufferImpl = new BufferImpl();
bufferImpl.appendBytes("你好世界......".getBytes());
socket.write(bufferImpl);
});
socket.closeHandler(handler->{
System.out.println("connect close :"+handler);
});
}).exceptionHandler(socket->{
socket.printStackTrace();
}).listen(8888).onSuccess(handler -> {
System.out.println("tcp server start up in port 8888 success!");
});
}
public static void main(String[] args) {
Vertx vertx2 = Vertx.vertx();
vertx2.deployVerticle(new TcpServer());
}
}
3. Client Demo
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.impl.BufferImpl;
import io.vertx.core.net.NetClient;
import io.vertx.core.net.NetSocket;
public class TcpClient extends AbstractVerticle {
@Override
public void start(Promise<Void> startPromise) throws Exception {
vertx
.createNetClient()
.connect(8888, "localhost")
.onComplete(socket->{
NetSocket result = socket.result();
result.handler(buffer->{
String content = buffer.toString("utf-8");
System.out.println("client received len:"+buffer.length()+",content:"+content);
});
result.closeHandler(handler->{
System.out.println("socket close....");
});
})
.onSuccess(handler->{
System.out.println("connect localhost:8888 tcp server success!");
BufferImpl bufferImpl = new BufferImpl();
bufferImpl.appendBytes("你好服务器!".getBytes());
handler.write(bufferImpl);
});
}
public static void main(String[] args) {
Vertx vertx2 = Vertx.vertx();
vertx2.deployVerticle(new TcpClient());
}
}
4. 测试
开启服务器 开启客户端
测试成功
|