62,615
社区成员
发帖
与我相关
我的任务
分享
public class Tst {
public static void main(String[] args){
try {
Socket socket=new Socket("127.0.0.1",9999);
String[] strs={new String("str1\r\n"),
new String("str2\r\n"),
new String("str3\r\n")};
OutputStream out=socket.getOutputStream();
int i=0;
while(i<3){
try {
Thread.sleep(3000);
System.out.println("准备发送!");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.write(strs[i].getBytes());
out.flush();
i++;
}
if(out!=null){
out.close();
}
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class TstServer {
private Selector selector = null;
static final int port = 9999;
private Charset charset = Charset.forName("UTF-8");
public void init() throws IOException
{
selector = Selector.open();
ServerSocketChannel server = ServerSocketChannel.open();
server.bind(new InetSocketAddress(port));
server.configureBlocking(false);
server.register(selector, SelectionKey.OP_ACCEPT);
while(true) {
int readyChannels = selector.select();
if(readyChannels == 0) continue;
Set selectedKeys = selector.selectedKeys();
Iterator keyIterator = selectedKeys.iterator();
while(keyIterator.hasNext()) {
SelectionKey sk = (SelectionKey) keyIterator.next();
keyIterator.remove();
dealWithSelectionKey(server,sk);
}
}
}
public void dealWithSelectionKey(ServerSocketChannel server,SelectionKey sk) throws IOException {
if(sk.isAcceptable())
{
SocketChannel sc = server.accept();
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_READ);
sk.interestOps(SelectionKey.OP_ACCEPT);
System.out.println("连接请求来自 :" + sc.getRemoteAddress());
}
//处理来自客户端的数据读取请求
if(sk.isReadable())
{
SocketChannel sc = (SocketChannel)sk.channel();
ByteBuffer buff = ByteBuffer.allocate(1024);
StringBuilder content = new StringBuilder();
try
{
int length=0;
while(true)
{
System.out.println("接收了一次, 大小为" + length);
buff.flip();
content.append(charset.decode(buff));
length=sc.read(buff);
if(length==0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(buff.toString().endsWith("\r\n")) break;
}
System.out.println("Server is listening from client " + sc.getRemoteAddress() + " data rev is: " + content);
sk.interestOps(SelectionKey.OP_READ);
}
catch (IOException io)
{
sk.cancel();
if(sk.channel() != null)
{
sk.channel().close();
}
}
}
}
public static void main(String[] args) throws IOException
{
new TstServer().init();
}
}