java超简单的tcp用法

只实现了回显功能,就是客户端发什么过来,服务端就将原数据返回.其中的处理是一线程对应一个客户端


服务端:

public class TcpServer {
    public static void main(String[] args) throws Exception{
        if (args.length!=1){
            throw new IllegalArgumentException("Parameter(s):<Port>");
        }
        int echoServPort=Integer.parseInt(args[0]);
        ServerSocket servSocket=new ServerSocket(echoServPort);
        Logger logger=Logger.getLogger("practical");
        Executor service= Executors.newFixedThreadPool(5);
        while (true){
            Socket socket=servSocket.accept();
            service.execute(new TcpHandler(socket,logger));
        }
    }
}

服务端处理请求类:

public class TcpHandler implements Runnable {
    private static final int BUFSIZE = 32;
    private static int TIMELIMIT=10000;
    private Socket socket;
    private Logger logger;
    public TcpHandler(Socket socket, Logger logger) {
        this.socket=socket;
        this.logger=logger;
    }
    public static void handleClient(Socket socket, Logger logger) {
        try {
            InputStream in=socket.getInputStream();
            OutputStream out=socket.getOutputStream();
            int recvMsgSize;
            int totalBytesEchoed=0;
            byte[] receiveBuf=new byte[BUFSIZE];
            long endTime=System.currentTimeMillis()+TIMELIMIT;
            int timeBoundMillis=TIMELIMIT;
            socket.setSoTimeout(timeBoundMillis);
            //Receive until client closes connection,indicate by -1
            while ((timeBoundMillis > 0) && ((recvMsgSize = in.read(receiveBuf)) != -1)) {
                out.write(receiveBuf, 0, recvMsgSize);
                totalBytesEchoed += recvMsgSize;
                timeBoundMillis = (int) (endTime - System.currentTimeMillis()) ;
                socket.setSoTimeout(timeBoundMillis);
            }
            logger.info("Client " + socket.getRemoteSocketAddress() + ", received " + totalBytesEchoed + " bytes.");
        }catch (IOException e){
            logger.log(Level.WARNING, "Exception in echo protocol", e);
        }finally {
            try {
                socket.close();
            }catch (IOException e){
            }
        }
    }
    @Override
    public void run() {
        handleClient(socket, logger);
    }
}

客户端:

public class TcpClient {
    public static void main(String[] args) throws IOException{
        if (args.length != 3) { // Test for correct # of args
            throw new IllegalArgumentException("Parameter(s): <Server> <Port> <Data>");
        }

        String destAddr = args[0]; // Destination address
        int destPort = Integer.parseInt(args[1]); // Destination port
        byte[] data = args[2].getBytes();// Data
        Socket socket = new Socket(destAddr, destPort);
        OutputStream out = socket.getOutputStream();
        out.write(data);  // Send the encoded string to the server

        // Receive the same string back from the server
        InputStream in = socket.getInputStream();
        int totalBytesRcvd = 0;  // Total bytes received so far
        int bytesRcvd;           // Bytes received in last read
        while (totalBytesRcvd < data.length) {
            if ((bytesRcvd = in.read(data, totalBytesRcvd,data.length - totalBytesRcvd)) != -1){
                totalBytesRcvd += bytesRcvd;
            }
        }  // data array is full

        System.out.println("Received: " + new String(data));
        socket.close();
    }
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值