socketchannel 编程(一)

来源:互联网 发布:淘宝十大平面女模特 编辑:程序博客网 时间:2024/06/04 01:19

1、 服务端

public class HelloWorld() {    public static void main(String[] args) throws IOException {        ServerSocketChannel channel = ServerSocketChannel.open();        channel.socket().bind(new InetSocketAddress(9999));        //配置连接模式: 阻塞或非阻塞        channel.configureBlocking(false);//非阻塞        while(true) {            SocketChannel socket = channel.accept();            if (socket != null ) {  //非阻塞的模式需要判断是否连接                ByteBuffer buf = ByteBuffer.allocate(48);                int byteRead = socket.read(buf);                if ( byteRead >= 1 ) {                    // others                }               }        }    }}//需要关闭socket和serversocketchannel

2、 客户端

public class HelloWorld() {    public static void main(String[] args) throws IOException {        InetAddress addr = InetAddress.getByName("127.0.0.1");        SocketAddress remote = new InetSocketAddress(addr, 9999);        SocketChannel clientChannel = SocketChannel.open(remote);        String msg = "fuck you shit";        ByteBuffer buf = ByteBuffer.allocate(200);        buf.clear();        buf.put(msg.getBytes());        buf.flip();        while (buf.hasRemaining()) {            clientChannel.write(buf);        }        clientChannel.close();    }}

3、网络七层模型:
应用层: Telnet/http/ftp/nfs/smtp
表示层: 加密,ascii
会话层: RPC/SQL
传输层: TCP/UDP/SPX
网络层:IP,IPX //报文
数据链路层: ATM/FDDI/Ethernet
物理层

0 0
原创粉丝点击