您的位置:首页 > 理论基础 > 计算机网络

TCP/NIO示例代码

2016-04-07 17:23 531 查看
package rpc;

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.nio.charset.Charset;
import java.util.Scanner;

public class NioClient {
private static Selector selector = null;
private static Charset charset = Charset.forName("UTF-8");
private ClientThread thread = new ClientThread();

public static void main(String[] args) throws IOException {
selector = Selector.open();
InetSocketAddress address = new InetSocketAddress("127.0.0.1",30000);
SocketChannel channel = SocketChannel.open(address);
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_READ);
new NioClient().thread.start();
Scanner scan = new Scanner(System.in);
while(scan.hasNextLine()){
String line = scan.nextLine();
channel.write(charset.encode(line));
}
}
private class ClientThread extends Thread{
public void run(){
try {
while(selector.select()>0){
for(SelectionKey key : selector.selectedKeys()){
selector.selectedKeys().remove(key);
if(key.isReadable()){
SocketChannel sc = (SocketChannel) key.channel();
System.out.println(" the remote port to which this socket is connected"+sc.socket().getPort());
System.out.println(" the Local port to which this socket is connected"+sc.socket().getLocalPort());
ByteBuffer buf = ByteBuffer.allocate(1024);
String content ="";
while(sc.read(buf)>0){
sc.read(buf);
buf.flip();
content += charset.decode(buf);
}
System.out.println("ClientThread:"+content);
key.interestOps(SelectionKey.OP_READ);

}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

}

package rpc;

import java.io.IOException;
import java.net.InetSocketAddress;
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 NioServer {

public static void main(String[] args) throws IOException {
//A selectable channel for stream-oriented listening sockets.
ServerSocketChannel server = ServerSocketChannel.open();
//implements an IP Socket Address (IP address + port number)
InetSocketAddress address = new InetSocketAddress("127.0.0.1", 30000);
//Binds the ServerSocket to a specific address
server.socket().bind(address);
//Adjusts this channel's blocking mode
server.configureBlocking(false);
//Opens a selector
Selector selector = Selector.open();
//Registers this channel with the given selector, returning a selection key
server.register(selector, SelectionKey.OP_ACCEPT);
Charset charset = Charset.forName("UTF-8");
while(selector.select()>0){
for(SelectionKey sk : selector.selectedKeys()){
//Removes the specified element from this set if it is present (optional operation).
selector.selectedKeys().remove(sk);
if(sk.isAcceptable()){
SocketChannel socketChannel = server.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
System.out.println(" the remote port to which this socket is connected"+socketChannel.socket().getPort());
System.out.println(" the Local port to which this socket is connected"+socketChannel.socket().getLocalPort());
sk.interestOps(SelectionKey.OP_ACCEPT);
}
if(sk.isReadable()){
SocketChannel socketChannel = (SocketChannel) sk.channel();
System.out.println(" the remote port to which this socket is connected"+socketChannel.socket().getPort());
System.out.println(" the Local port to which this socket is connected"+socketChannel.socket().getLocalPort());
ByteBuffer buff = ByteBuffer.allocate(1024);
String content ="";
try {
while(socketChannel.read(buff)>0){
buff.flip();
content += charset.decode(buff);
}
System.out.println("server receive:"+content);
sk.interestOps(SelectionKey.OP_READ);
} catch (Exception e) {
sk.cancel();
if(sk.channel()!=null)
sk.channel().close();
}
//写回
if(content.length()>0){
for(SelectionKey key :selector.keys()){
Channel targetChannel = key.channel();
if(targetChannel instanceof SocketChannel){
SocketChannel channel = (SocketChannel) targetChannel;
channel.write(charset.encode(content+"server写入"));
}
}
}
}
}
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  NIO java java通信