BIO多线程编程

package com.dashuf.caes.job.batch;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class BIOdemo {
    
    public static void main(String[] args){
        try {
            Start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void Start() throws Exception{
        new Thread(() -> {
            try {
                ServerClass.startServer();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
        Thread.sleep(2000);
        new Thread(() -> {
            Client client = new Client();
            client.connect();
            Client client2 = new Client();
            client2.connect();
            client.send("123");
            client.send("456");
            client2.send("789");
        }).start();
        Thread.sleep(2000);
        ServerClass.broadcast("123123123123");
        Thread.sleep(10000);
    }
}

class ServerClass{

    private static Map<String,Socket> socketMap = new HashMap<>();
    private static ServerSocket serverSocket = null;

    public static void startServer () throws Exception {
        serverSocket = new ServerSocket(8877);
        while(true) {
            final Socket accept = serverSocket.accept();
            System.out.println(1);
            String IpPort = accept.getInetAddress()+":"+accept.getPort();
            if (socketMap.get(IpPort) != null) {
                int count = 1;
                for (String ip : socketMap.keySet()) {
                    if (ip.startsWith(IpPort)) {
                        count++;
                    }
                }
                String newIpPort = IpPort + String.valueOf(count);
                socketMap.put(newIpPort,accept );
            } else {
                socketMap.put(IpPort,accept);
            }
            new Thread(new ServerDealThread(accept)).start();
        }
    }

    public static void broadcast(String message){
        for (Map.Entry<String,Socket> entry: socketMap.entrySet()) {
            Socket socket = entry.getValue();
            if (socket != null) {
                System.out.println("广播:"+entry.getKey());
                PrintWriter out = null;
                try {
                    out = new PrintWriter(socket.getOutputStream());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                out.println(message);
                out.flush();
            } else{
                System.out.println(entry.getKey()+"已注销,无法广播");
            }
        }

    }
}

class ServerDealThread implements Runnable {

    Socket socket = null;

    public ServerDealThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream());
            while (true) {
                String input;
                if ((input = in.readLine()) == null) {
                    break;
                } else {
                    System.out.println("服务器收到:" + input);
                }
                out.println("服务器已收到:"+input);
                out.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                socket = null;
            }
        }
    }
}


class Client {
    private static int port = 8877;
    private static String ip = "127.0.0.1";

    private Socket socket=null;

    public void connect() {
        try{
            if (socket == null) {
                socket = new Socket(ip, port);
            }
            new Thread(()-> {
                try {
                    String str = null;
                    BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    while ((str = reader.readLine()) != null) {
                        System.out.println("客户端收到:" + str);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    public void send(String input) {
        try {
            PrintWriter writer = new PrintWriter(socket.getOutputStream());
            writer.println(input);
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值