Java TCP实现简单的即时通讯
2021-05-29 16:04
public static void main(String[] args) {
    ServerSocket serverSocket = null;
    Socket socket = null;
    InputStream inputStream = null;
    ByteArrayOutputStream outputStream = null;    try {
        //创建一个连接
        serverSocket = new ServerSocket(9999);
        while (true){
            //等待连接
            socket = serverSocket.accept();
            //读取信息
            inputStream = socket.getInputStream();
            outputStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int len;
            if((len=inputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
            }
            System.out.println(outputStream.toString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if(outputStream!=null){
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(inputStream!=null){
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(socket!=null){
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(serverSocket!=null){
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
                    
            上一篇:spring循环依赖
下一篇:php文件包含的几种方式总结