網絡編程之Java BIO 概念及代碼使用demo

JAVA BIO Socket 服務端代碼demo

代碼只有Server端測試用的 telnet工具,代碼後邊有測試過程。

package bio.test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestBioServer {
	/**
	 * BIO 多線程監聽連接
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		
		//這裏使用try resouce 管理資源
		//創建ServerSocket
		try (ServerSocket ss = new ServerSocket(9090)){
			System.out.println("服務器啓動...");
			//創建線程池
			ExecutorService pool = Executors.newCachedThreadPool();
			
			while(true){
				System.out.println("等待連接...");
				//等待客戶段連接 沒有連接會阻塞
				final Socket socket = ss.accept();
				System.out.println("連接到一個客戶端");
				//異步處理數據
				pool.execute(new Runnable() {
					
					@Override
					public void run() {
						handle(socket);
					}
				});
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		
	}
	/**
	 * 接受數據
	 * @param socket
	 */
	public static void handle(Socket socket){
		try (Socket socketnew = socket){
			OutputStream out = socket.getOutputStream();
			out.write("連接成功:".getBytes());
			System.out.println("當前線程ID:"+Thread.currentThread().getId() +" 當前線程name: "+Thread.currentThread().getName());
			InputStream in = socketnew.getInputStream();
			byte[] data = new byte[1024];
			System.out.println("等待輸入內容...");
			int len = 0 ;
			//獲取流中的數據  這裏如果沒有數據 會阻塞
			while((len= in.read(data))!=-1){
				System.out.println(new String(data,0,len));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

使用測試:

啓動服務器端

啓動服務器端

使用telnet 客戶端連接併發送數據

運行telnet
在這裏插入圖片描述在這裏插入圖片描述
在這裏插入圖片描述
服務器端收到消息並打印結果:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章