使用new io 的socket

服务器端(非阻塞):

package org.snake.socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {

	private static final int DEFAULT_PORT = 12346;		// 默认端口号
	private static ExecutorService exec = Executors.newFixedThreadPool(10);		
	private static final String HELLO = "Hello,Client";

	public static void main(String[] args) throws IOException {
		
		ServerSocketChannel ssc = ServerSocketChannel.open();	//  开启一个 server-socket通道
		ssc.configureBlocking(false);							// 设置该通道为非阻塞模式
		ServerSocket ss = ssc.socket();							// 取得与该通道关联的server socket
		InetSocketAddress ina = new InetSocketAddress(DEFAULT_PORT); // 用给定的端口号创建一个socket-address
		ss.bind(ina);		// 将该通道绑定到指定的地址
		
		final ByteBuffer buff = ByteBuffer.allocate(128);	// 分配一个容量为128字节的缓冲区
		
		while(true) {
			final SocketChannel sc = ssc.accept();	// 因为该通道为非阻塞模式,所以会立即返回,返回值可能为null
			if(sc == null) {
//				System.out.println("当前没有连接进入");
			}
			else {
				// 另起一个线程来处理客户请求
				exec.execute(new Runnable() {
					@Override
					public void run() {
						// 写向客户端
						buff.clear();
						buff.put(HELLO.getBytes());
						buff.flip();
						try {
							sc.write(buff);
						} catch (IOException e) {
							e.printStackTrace();
						}
						
						//读取客户端
						buff.clear();
						try {
							
							sc.read(buff);
						} catch (IOException e) {
							e.printStackTrace();
						}
						buff.flip();
						while(buff.hasRemaining()) {
							System.out.print((char)buff.get());
						}
						System.out.println();
					}
				});
			}
		}

		
		
	}
}

客户端(阻塞式):

package org.snake.socket;

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

public class Client {

	private static final int DEFAULT_PORT = 12346;
	private static final String DEFAULT_IP = "localhost";
	private static final String HELLO = "Hello,Server";
	
	public static void main(String[] args) throws IOException{
		
		SocketChannel sc = SocketChannel.open();
		InetSocketAddress ina = new InetSocketAddress(DEFAULT_IP, DEFAULT_PORT);
		sc.connect(ina);		// 该方法会阻塞,因为该通道为阻塞模式
		
		//写到服务器
		ByteBuffer buff = ByteBuffer.allocate(128);
		buff.put(HELLO.getBytes());
		buff.flip();
		sc.write(buff);
		
		//读取服务器
		buff.clear();
		sc.read(buff);
		buff.flip();
		while(buff.hasRemaining()) {
			System.out.print((char)buff.get());
		}
		
		sc.close();		//关闭通道
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值