package testclient1;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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.Timer;
import java.util.TimerTask;
public class ChannelClient {
//注释详见com.telesound.nio.server.ClientThread.java
private SocketChannel socketChannel;
private final String HOST = "192.168.11.80";
private final int PORT = 5678;
private Selector selector = null;
private InputStream in;
private OutputStream out;
public ChannelClient() throws IOException {
// TODO Auto-generated constructor stub
initialize();//初始化
comhandNet();
}
private void comhandNet() {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
String send = "心跳访问";
try {
sendData(send.getBytes("UTF-16"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 0, 10000);
}
//初始化客户端连接
private void initialize() throws IOException {
// TODO Auto-generated method stub
//打开监听通道
socketChannel = SocketChannel.open(new InetSocketAddress(HOST,PORT));
//设置非阻塞模式
socketChannel.configureBlocking(false);
//打开选择器并注册到信道
selector = Selector.open();
socketChannel.register(selector,SelectionKey.OP_READ|SelectionKey.OP_WRITE);//读取集
//启动读取的线程----
new ChannelReadClient(selector);
}
/**
* 发送数据到服务器
* @param byout
* @throws IOException
*/
public void sendData(byte[] byout) throws IOException{
ByteBuffer writeBuf = ByteBuffer.wrap(byout);
socketChannel.write(writeBuf);
// out = socketChannel.socket().getOutputStream();
// out.write(byout);
}
public static void main(String[] args) throws IOException {
ChannelClient c = new ChannelClient();
String send = "客户端访问";
c.sendData(send.getBytes("UTF-16"));
}
}
nio异步长连接服务端与客户端
4星 · 超过85%的资源 需积分: 10 44 浏览量
2010-04-15
20:49:14
上传
评论 1
收藏 12KB RAR 举报
winbps
- 粉丝: 30
- 资源: 8
最新资源
- 散斑结构光测试图像-对应博客:https://mp.csdn.net/mp-blog/creation/editor/13817
- 20220823-1000-ts.dat
- Galaxy10CNN实现星系图像分类项目深度学习环境配置
- DVB-S2:GCS组帧数据.dat
- 基于强化学习Q-Learning方法实现机器人走迷宫源码.zip
- numpy+pandas_basics.ipynb
- 网络安全-Diffie Hellman密钥协商
- 双H桥电机驱动L298N芯片AD集成库ALTIUM库(原理图库+PCB封装库)文件.zip
- 计算机组成原理实验;16位运算器ALU CPU设计
- 毕设绝技 - 4天玩乐完成商城系统完整资料day04
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
- 1
- 2
前往页