客户端非阻塞式通信(Java Socket Channel)

服务端代码(阻塞式):

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;

/**
 * 服务器端阻塞式IO(Java ServerSocket)
 * @author Bright Lee
 */
public class ServerSocketTest {

	public static void main(String[] args) {
		ServerSocket serverSocket = null;
		Socket socket = null;
		InputStream in = null;
		try {
			serverSocket = new ServerSocket(6666);
			socket = serverSocket.accept();
			
			SocketAddress clientAddress = socket.getRemoteSocketAddress();
			System.out.println("有客户端连接:" + clientAddress);
			
			in = socket.getInputStream();
			
			int value = -1;
			
			while ((value = in.read()) != -1) {
				char ch = (char) value;
				System.out.print(ch);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(serverSocket, socket, in);
		}
	}
	
	private static void close(ServerSocket serverSocket, Socket socket, InputStream in) {
		try {
			if (in != null) {
				in.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			if (socket != null) {
				socket.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			if (serverSocket != null) {
				serverSocket.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

客户端代码(非阻塞式):

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * 客户端非阻塞式IO(Java SocketChannel)
 * @author Bright Lee
 */
public class SocketChannelTest {

	public static void main(String[] args) {
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		SocketChannel socketChannel = null;
		try {
			socketChannel = SocketChannel.open();
			socketChannel.configureBlocking(false);
			socketChannel.connect(new InetSocketAddress("127.0.0.1", 6666));
			
			if (socketChannel.finishConnect()) {
				String info = "I'm a client! My number is " + System.currentTimeMillis();
				buffer.clear();
				buffer.put(info.getBytes("UTF-8"));
				buffer.flip();
				while (buffer.hasRemaining()) {
					socketChannel.write(buffer);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (socketChannel != null) {
					socketChannel.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}

先运行服务端代码(ServerSocketTest.java),再运行客户端代码(SocketChannelTest.java),服务端打印信息如下:
有客户端连接:/127.0.0.1:51564
I’m a client! My number is 1547276873269

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值