发送数据
//1.创建Socket对象
//细节:在创建对象的同时会链接服务端
// 如果链接不上,代码会报错
Socket socket = new Socket("127.0.0.1",10000);
//2.可以从连接通道中获取输出流
OutputStream os = socket.getOutputStream();
//写出数据
os.write("hello".getBytes());
//释放资源
os.close();
socket.close();
接收数据
//1.接收数据 //创建对象ServerSocket ServerSocket ss = new ServerSocket(10000); //监听客户端的链接 Socket socket = ss.accept(); //从链接通道中获取输入流读取数据 InputStream is = socket.getInputStream(); //字节流转换为字符流 能更快传输数据 InputStreamReader isr = new InputStreamReader(is); //字符缓冲流 BufferedReader br = new BufferedReader(isr); int b = 0; while ((b = br.read()) != -1) { System.out.print((char) b); } //释放资源 socket.close(); ss.close();