java nio 客户端没有收到,远端识别的端口号貌似不一致

天边龙一条 2018-01-05 10:37:42

服务端代码
/**
* Created by zhang on 2018/1/3.
*/
public class MultiplexerTimeServer implements Runnable{
private Selector selector;
private ServerSocketChannel serverSocketChannel;
private volatile boolean stop;
public MultiplexerTimeServer(int port) {
try {
selector =Selector.open();
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(port),1024);
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("The time server is start in port : "+port);

} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
public void stop(){
this.stop =true;
}
@Override
public void run() {
while (!stop){
try {
selector.select(1000);
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> it = selectionKeys.iterator();
SelectionKey key = null;
while (it.hasNext()){
key = it.next();
it.remove();
try {
handleInput(key);
} catch (Exception e) {
if(key!=null){
key.cancel();
if (key.channel()!=null){
key.channel().close();
}
}
}
}
} catch (Throwable t) {
t.printStackTrace();
}
}
//多路复用器关闭后,所有注册在上面的Channel 和pipe等资源会被自动去注册关闭,所以不需重复释放资源
if(selector !=null){
try {
selector.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

private void handleInput(SelectionKey key) throws Exception{
if (key.isValid()){
//处理新接入的请求消息
if (key.isAcceptable()){
//accept new connection
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
SocketChannel sc = ssc.accept();
sc.configureBlocking(false);
//add new connection to the selector
sc.register(selector,SelectionKey.OP_READ);
}
if (key.isReadable()){
//read the data
SocketChannel sc = (SocketChannel) key.channel();
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
int readBytes = sc.read(readBuffer);
if (readBytes>0){
readBuffer.flip();
byte[] bytes = new byte[readBuffer.remaining()];
readBuffer.get(bytes);
String body = new String(bytes,"UTF-8");
System.out.println("The time Server receive order : "+body);
String currentTime ="QUERY TIME ORDER".equalsIgnoreCase(body)? new Date(System.currentTimeMillis()).toString():" BAD ORDER";
System.out.println("local "+sc.getLocalAddress()+", remote"+sc.getRemoteAddress());
doWrite(sc,currentTime);
}else if (readBytes < 0){
//对链路端关闭
key.cancel();
sc.close();
}else {
;//读到0字节,忽略
}
}
}
}

private void doWrite(SocketChannel sc, String response) throws Exception{
if ( response!= null && response.trim().length()>0){
byte[] bytes = response.getBytes();
ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
writeBuffer.put(bytes);
writeBuffer.flip();
sc.write(writeBuffer);
}
}
}
package NIO;

/**
* Created by zhangguanlong on 2017/12/28.
*/
import BIO.TimeServerHandler;
import BIO.TimeServerHandlerExecutePool;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class TimeServer {
public static void main(String[] args) throws IOException {
int port = 8380;
if (args != null&& args.length>0) {
port=Integer.valueOf(args[0]);
}
MultiplexerTimeServer timeServer = new MultiplexerTimeServer(port);
new Thread(timeServer,"NIO-mMultiplexerTimeServer-001").start();

}

}
客户端
package NIO;

import com.sun.org.apache.xpath.internal.SourceTree;

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.SocketChannel;
import java.util.Iterator;
import java.util.Set;


public class TimeClientHandle implements Runnable {
private String host;
private int port;
private Selector selector;
private SocketChannel socketChannel;
private volatile boolean stop;

public TimeClientHandle(String host, int port) {
this.host = host == null ? "127.0.0.1": host;
this.port = port;
System.out.println("TimeClientHandle port is "+this.port);
try {
selector=Selector.open();
socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}

@Override
public void run() {
try {
doConnect();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
while (!stop){
try {
selector.select(1000);
Set<SelectionKey> selectionKeys =selector.selectedKeys();
Iterator<SelectionKey> it = selectionKeys.iterator();
SelectionKey key = null;
while (it.hasNext()){
key = it.next();
it.remove();
try {
handleInput(key);
} catch (Exception e) {
if (key == null) {
key.cancel();
if (key.channel() != null) {
key.channel().close();
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
if (selector!=null){
try {
selector.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

private void handleInput(SelectionKey key) throws Exception{

if (key.isValid()){
SocketChannel sc = (SocketChannel) key.channel();
if (key.isConnectable()){
if (sc.finishConnect()){
sc.register(selector,SelectionKey.OP_READ);
doWrite(sc);
}else {
System.exit(1);
}
if (key.isReadable()){
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
int readBytes = sc.read(readBuffer);
if (readBytes>0){
readBuffer.flip();
byte[] bytes = new byte[readBuffer.remaining()];
readBuffer.get(bytes);
String body = new String(bytes,"UTF-8");
System.out.println("Now is : "+body);
this.stop =true;
}else if (readBytes < 0){
//关闭链路端
key.cancel();
sc.close();
}else {
//读到0字节 忽略
;
}
}
}
}

}


private void doConnect() throws IOException {
//连接成功注册到多路复用器
System.out.println("port"+port);
if (socketChannel.connect(new InetSocketAddress(host,port))){
socketChannel.register(selector, SelectionKey.OP_READ);
System.out.println(socketChannel.getLocalAddress()+","+socketChannel.getRemoteAddress());
doWrite(socketChannel);
}else {
socketChannel.register(selector,SelectionKey.OP_CONNECT);
}
}

private void doWrite(SocketChannel socketChannel) throws IOException {
byte[] req ="QUERY TIME ORDER".getBytes();
ByteBuffer writeBuffer =ByteBuffer.allocate(req.length);
writeBuffer.put(req);
writeBuffer.flip();
socketChannel.write(writeBuffer);
if (!writeBuffer.hasRemaining()) {
System.out.println("Send order 2 server :"+socketChannel.getRemoteAddress()+" succeed.");
}
}
}
package NIO;

import java.io.*;
import java.net.Socket;

public class TimeClient {
public static void main(String[] args) {
int port = 8380;
if (args == null&&args.length>0) {
port = Integer.valueOf(args[0]);
}
new Thread(new TimeClientHandle("127.0.0.1",port),"TimeClient-001").start();

}
}
结果


服务端打印的是50270,客户端确实50262,虽然是一台机器上,但是不是不正常
...全文
203 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

50,532

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧