JAVA服务器/客户端编程之阻塞式服务器

最近在学java,感觉比起c++的TCP通信要简单多了呀

package my_network_test.zuse;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.*;

public class EchoServer {
    private ServerSocketChannel serverSocketChannel;
    private ExecutorService executorService; //线程池
    private final int POOL_SIZE=4; //单CPU工作时线程的数量

    public EchoServer() throws IOException {
        //serverSocket=new ServerSocket(port);
        serverSocketChannel=ServerSocketChannel.open();
        serverSocketChannel.socket().setReuseAddress(true);
        int port = 4444;
        serverSocketChannel.socket().bind(new InetSocketAddress(port)); //把服务器进程与一个本地端口绑定
        //创建线程池
        executorService=Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*POOL_SIZE);
        System.out.println("服务器启动...");

    }

    public void service(){
        while(true){
            SocketChannel socket;
            try{
                socket=serverSocketChannel.accept();
               executorService.execute(new Handle(socket));

            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }


    static public void main(String[] args) throws IOException{
        new EchoServer().service();
    }
}

class Handle implements Runnable{
    private final SocketChannel socketChannel;
    private Socket socket;

    public Handle(SocketChannel socketChannel){
        this.socketChannel=socketChannel;
    }

    public void run(){
        try{
            socket=socketChannel.socket(); //获得与socketChannel关联的Socket对象
            System.out.println("建立新连接:"+socket.getInetAddress()+":"+socket.getPort());
            BufferedReader brSocket=new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter pw=new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),true);
            String msg;
            while((msg=brSocket.readLine())!=null){
                if(msg.equals("end")) {
                    System.out.println("客户端"+socket.getPort()+"已断开连接");
                    break;
                }
                System.out.println("来自客户端"+socket.getPort()+":"+msg);
                pw.println("服务器收到!");
            }
        }catch (IOException e){
            System.out.println("客户端"+socket.getPort()+"已断开连接");
        }finally {
            try{
                if(socket!=null) socket.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值