一、BIO模式下的端口转发思想
需求:需要实现是个客户端的消息可以发送给所有的客户端接收.(群聊实现)
我们每一个客户端都会和服务器端建立一个socket通道,这样服务器端和客户端就能够实现通信。为了让服务器端知道我们当前有多少个socket正在运行,我们就建立一个socket集合。把当前连接的客户端socket存入到一个所谓的在线socket集合中保存,这样服务器端就知道那些客户端和服务器端正在进行通信。
当一个客户端A发送消息给服务器端的时候,当服务器端接收到消息以后,就可以变量socket集合,给每一个客户端将客户端A发送的消息发送过去,进而实现群聊。
服务器端
public class Client {public static void main(String[] args) throws Exception {Socket socket = new Socket("127.0.0.1", 8080);//开启数据发送线程new sendMessThread(socket).start();//开启数据接收线程new readerThread(socket).start();}
}// 发送数据到服务器
class sendMessThread extends Thread{private Socket socket;public sendMessThread(Socket socket){this.socket = socket;}@Overridepublic void run() {super.run();//写操作Scanner scanner=null;OutputStream os= null;try {scanner=new Scanner(System.in);os= socket.getOutputStream();String in="";while (true){String message = scanner.nextLine();os.write(message.getBytes());//4.关闭os.flush();}} catch (IOException e) {e.printStackTrace();}scanner.close();try {os.close();} catch (IOException e) {e.printStackTrace();}}
}
// 接收服务器的消息
class readerThread extends Thread{private Socket socket;public readerThread(Socket socket){this.socket = socket;}@Overridepublic void run(){try {//1、从socket中去获取当前客户端的输入流InputStream inputStream = socket.getInputStream();byte[] buf = new byte[1024];int len = 0;while ((len = inputStream.read(buf)) != -1) {System.out.println(new String(buf, 0, len,"UTF-8"));}}catch (Exception e){}}
}
客户端
public class Client {public static void main(String[] args) throws Exception {Socket socket = new Socket("127.0.0.1", 8080);//开启数据发送线程new sendMessThread(socket).start();//开启数据接收线程new readerThread(socket).start();}
}// 发送数据到服务器
class sendMessThread extends Thread{private Socket socket;public sendMessThread(Socket socket){this.socket = socket;}@Overridepublic void run() {super.run();//写操作Scanner scanner=null;OutputStream os= null;try {scanner=new Scanner(System.in);os= socket.getOutputStream();String in="";while (true){String message = scanner.nextLine();os.write(message.getBytes());//4.关闭os.flush();}} catch (IOException e) {e.printStackTrace();}scanner.close();try {os.close();} catch (IOException e) {e.printStackTrace();}}
}
// 接收服务器的消息
class readerThread extends Thread{private Socket socket;public readerThread(Socket socket){this.socket = socket;}@Overridepublic void run(){try {//1、从socket中去获取当前客户端的输入流InputStream inputStream = socket.getInputStream();byte[] buf = new byte[1024];int len = 0;while ((len = inputStream.read(buf)) != -1) {System.out.println(new String(buf, 0, len,"UTF-8"));}}catch (Exception e){}}
}