输入数据
//1.创建Socket对象
//细节:在创建对象的同时会链接服务端
// 如果链接不上,代码会报错
Socket socket = new Socket("127.0.0.1",10000);
//写出数据
String str ="你好你好";
OutputStream os = socket.getOutputStream();
os.write(str.getBytes());
//写出一个结束标记
socket.shutdownOutput();
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();
读取数据
//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; //read方法从连接通道读取数据 //单数,需要一个结束的标记,此时循环才能停止 //否则,程序就会一直停在read方法这里,等待下面的数据 while ((b = br.read()) != -1) { System.out.print((char) b); } //写出数据 String str ="你有多好呀"; OutputStream os = socket.getOutputStream(); os.write(str.getBytes()); //释放资源 socket.close(); ss.close();