BIO服务端:
public class BIOServer {
ServerSocket server;
//服务器
public BIOServer(int port){
try {
//把Socket服务端启动
server = new ServerSocket(port);
System.out.println("BIO服务已启动,监听端口是:" + port);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 开始监听,并处理逻辑
* @throws IOException
*/
public void listener() throws IOException{
//死循环监听
while(true){
//虽然写了一个死循环,如果一直没有客户端连接的话,这里一直不会往下执行
Socket client = server.accept();//等待客户端连接,阻塞方法
//拿到输入流,也就是乡村公路
InputStream is = client.getInputStream();
//缓冲区,数组而已
byte [] buff = new byte[1024];
int len = is.read(buff);
//只要一直有数据写入,len就会一直大于0
if(len > 0){
String msg = new String(buff,0,len);
System.out.println("收到" + msg);
}
//
// while (len != -1){
// String msg = new String(buff,0,len);
// System.out.println("收到" + msg);
// }
}
}
public static void main(String[] args) throws IOException {
new BIOServer(8081).listener();
}
}
BIO客户端:
public class BIOClient2 {
public static void main(String[] args) throws UnknownHostException, IOException {
try{
//开一条乡村公路
Socket client = new Socket("localhost", 8081);
//输出流通道打开
OutputStream os = client.getOutputStream();
//产生一个随机的字符串,UUID
String name = UUID.randomUUID().toString();
//发送给服务端
os.write(name.getBytes());
os.close();
client.close();
}catch(Exception e){
}
}
}
server端: 使用
if(len > 0){
String msg = new String(buff,0,len);
System.out.println("收到" + msg);
}
客户端发送一次,则服务器只打印一次。
使用:while时
while (len != -1){
String msg = new String(buff,0,len);
System.out.println("收到" + msg);
}
客户端发送一次,则服务器会一直循环打印传输的uuid
本文深入探讨了BIO(Blocking I/O)在网络通信中的应用,包括服务端与客户端的实现原理。通过具体代码示例,展示了如何在Java中创建BIO服务端与客户端,以及它们之间的数据交互过程。特别关注了不同数据读取方式下,服务端对客户端发送数据的响应差异。
1539

被折叠的 条评论
为什么被折叠?



