package newtest;

 import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset; public class TcpServer
{
//用于检测所有Channel状态的selector
private Selector selector = null;
//定义编码格式
private Charset charset = Charset.forName("UTF-8"); public void init()throws IOException
{
selector = Selector.open();
//通过open方法来打开一个未绑定的ServerSocketChannel实例
ServerSocketChannel server = ServerSocketChannel.open();
InetSocketAddress isa = new InetSocketAddress("127.0.0.1", 8899);
//将该ServerSocketChannel绑定到指定IP地址
server.socket().bind(isa);
//设置ServerSocket以非阻塞方式工作
server.configureBlocking(false);
//将Server注册到指定Selector对象
server.register(selector, SelectionKey.OP_ACCEPT); while(selector.select() > 0)
{
//依次处理Selector上的每个已选择的SelectionKey
for(SelectionKey sk : selector.selectedKeys())
{
//从selector上的已选择Key集中删除正在处理的SelectionKey
selector.selectedKeys().remove(sk);
//如果sk对应的通道包含客户端的连接请求
if(sk.isAcceptable())
{
//调用accept方法接受连接,产生服务器端对应的SocketChannel
SocketChannel sc = server.accept();
//设置非阻塞方式工作
sc.configureBlocking(false);
//将该SocketChnnel也注册到selector
sc.register(selector, SelectionKey.OP_READ);
//将sk对应的Channel设置成准备接受其它请求
sk.interestOps(SelectionKey.OP_ACCEPT);
}
//如果sk对应的通道有数据需要读取
if(sk.isReadable())
{
//获取该SelectionKey对应的Channel,该Channnel中有可读的数据
SocketChannel sc = (SocketChannel)sk.channel();
//定义准备执行读取数据的ByteBuffer
ByteBuffer buff = ByteBuffer.allocate(1024);
String content = "";
//开始读数据
try
{
while(sc.read(buff) > 0)
{
buff.flip();
content += charset.decode(buff);
}
//打印从该sk对应的Channel里读到的数据
System.out.println("消息:" + content);
//将sk对应的Channel设置成准备下一次读取
sk.interestOps(SelectionKey.OP_READ);
}
//如果捕捉到该sk对应的Channel出现了异常,即表明该Channel对应的Client出现了问题
//所以从Selector中取消sk的注册
catch(IOException ex)
{
//从Selector中删除指定的SelectionKey
sk.cancel();
if(sk.channel() != null)
{
sk.channel().close();
}
}
// throw new IOException();
//如果content的长度大于0,即聊天信息不为空
if(content.length() > 0)
{
//遍历该selector里注册的所有selectionKey
for(SelectionKey key : selector.keys())
{
//获取该channel是SocketChannel对象
Channel targetChannel = key.channel();
if(targetChannel instanceof SocketChannel)
{
//将读到的内容写入该Channel中
SocketChannel dest = (SocketChannel)targetChannel;
dest.write(charset.encode(content));
}
}
}
}
}
}
} public static void main(String[] args)throws IOException
{
System.out.println("===========TCP的server端启动=============");
new TcpServer().init();
}
}
package com.springboot.springbootswagger.client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException; public class TcpClient {
// initialize socket and input output streams
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null; // constructor to put ip address and port
public TcpClient(String address, int port)
{
// establish a connection
try
{
socket = new Socket(address, port);
System.out.println("Connected"); // takes input from terminal
input = new DataInputStream(System.in); out = new DataOutputStream(socket.getOutputStream());
}
catch(UnknownHostException u)
{
System.out.println(u.toString());
}
catch(IOException i)
{
System.out.println(i);
} // 待读入的String
String line = ""; // 一直读到Over字符停止
while (!line.equals("Over"))
{
try
{
line = input.readLine();
out.writeUTF(line);
}
catch(IOException i)
{
System.out.println(i);
}
} // 关闭连接
try
{
input.close();
out.close();
socket.close();
}
catch(IOException i)
{
System.out.println(i);
}
} public static void main(String args[])
{
TcpClient client = new TcpClient("127.0.0.1", 8899);
}
}

最新文章

  1. ASP.NET Core Loves JavaScript
  2. Book LIst
  3. POJ 1743 Musical Theme (后缀数组,求最长不重叠重复子串)(转)
  4. jstl表达式使用方法
  5. Spring 中JCA CCI分析--转载
  6. 使用POI插件,提取导出excel的工具类
  7. 手动安装英特尔® 凌动™ Android* x86 模拟器映像
  8. ssh框架的小实例(用户登录)
  9. zabbix 告警小试
  10. Crypto加密解密
  11. 中国剩余定理 CRT
  12. 解决 Ubuntu 经常 卡死
  13. Liferay7 BPM门户开发之24: Liferay7应用程序安全
  14. 诡异的 ERROR 1045 (28000): Access denied for user 错误
  15. AngularJS图片上传功能实践
  16. 别人家的PS系列又来了!!!
  17. 剑指offer:矩形覆盖
  18. 搭建J2EE开发平台-Eclipse+MySql+tomcat
  19. centos下安装lnmp各个版本的几种方法
  20. python:常用模块二

热门文章

  1. 牛客练习赛39 B.选点
  2. poj 2762
  3. CodeForces - 999C Alphabetic Removals
  4. servlet 中session的使用方法(创建,使用)
  5. OpenDayLight Beryllium版本 下发流表实现hardtimeout
  6. elasticsearch sql插件配置(5.0及以上版本)
  7. Visual Studio Code(VS Code)命令行的使用(1)
  8. Flutter移动电商实战 --(36)FlutterToast插件使用
  9. git如何将一个远程仓库的某个分支拉取到当前分支?
  10. vue 自定义 提示框(Toast)组件