用OIO实现一个简单客户端。具体代码如下:
package com.zhshl.nio; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * zhshl 2018/10/5 */ public class OIOServer { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(10010); ExecutorService executorService = Executors.newCachedThreadPool(); System.out.println("服务器启动成功"); while(true){ //获取一个套字节(阻塞) final Socket socket = serverSocket.accept(); System.out.println("来了一个新的客户端"); executorService.execute(new Runnable() { public void run() { handler(socket); } }); } } /** * 读取数据 * @param socket */ public static void handler(Socket socket) { try { byte[] bytes = new byte[1024]; InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream(); PrintWriter printWriter = new PrintWriter(outputStream); while(true){ //读取数据(阻塞) int read = inputStream.read(bytes); if(read != -1){ System.out.println(new String(bytes, 0, read,"GBK")); printWriter.print("你好:"+socket.getInetAddress()+"," + "你刚刚发送的消息我已经接收到了。发送的内容为:" + new String(bytes, 0, read,"GBK")); printWriter.flush(); }else{ break; } } } catch (Exception e) { e.printStackTrace(); }finally{ try { System.out.println("socket关闭"); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }