3.BIO的多发和多收机制
1.如何实现客户端多次发消息,服务端多次接收的情况呢
1.服务端
/**
* 目标:客户端发送消息,服务端接收消息
*/
public class Server {
public static void main(String[] args) {
try {
System.out.println("======服务端启动=======");
//1.定义一个ServerSocket对象进行服务端的端口注册
ServerSocket ss=new ServerSocket(9999);
System.out.println("======服务端等待连接.......");
//2.监听客户端的Socket连接请求
Socket socket = ss.accept();
//3.从Socket管道中得到一个字节输入流对象
InputStream inputStream=socket.getInputStream();
//4.把字节输入流包装称一个缓冲字符输入流
BufferedReader br=new BufferedReader(new InputStreamReader(inputStream));
String msg;
//重点1:这里使用while
while ( (msg=br.readLine())!=null){
System.out.println("服务端接收到的消息:"+msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.客户端:
public class Client {
public static void main(String[] args) {
try {
//1.创建Socket对象请求服务端的连接
Socket client = new Socket("127.0.0.1", 9999);
//2.从Scoket对象中获取一个字节输出流
OutputStream outputStream = client.getOutputStream();
//3.把字节流包装成一个打印流
PrintStream ps = new PrintStream(outputStream);
Scanner scanner = new Scanner(System.in);
//重点2:这里使用while(true),里面可以对应
while (true) {
System.out.print("客户端1--->请讲:");
String msg = scanner.nextLine();
ps.println(msg);
ps.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.那如果多个客户端连接呢??