JAVAWEB 初识服务器-web

web服务软件的作用:把本地的资源共享给外部访问。

web服务器:PC机器安装一个具有web服务的软件,称之为web服务器

下面来看代码:

/**
 * socket服务器端程序
 * 这断代码作用是开启了一个的简单的服务器程序
 */
public class Server {

    public static void main(String[] args) throws Exception {
        //1.创建ServerSocket
        ServerSocket server = new ServerSocket(8080);//端口8080

        System.out.println("服务器已经启动成功....");

        while(true){
            //2.接收客户端的连接
            Socket socket = server.accept();

            //3.读取本地的test.html文件
            FileInputStream in = new FileInputStream(new File("/Users/yinxian/Desktop/html.html"));//html的路径

            //4.构建数据输出通道
            OutputStream out = socket.getOutputStream();

            //5.发送数据
            byte[] buf = new byte[1024];
            int len = 0;
            while( (len=in.read(buf))!=-1 ){
                out.write(buf, 0, len);
            }

            //6.关闭资源
            out.close();
            in.close();
        }
    }
}

我们在浏览器中输入http://localhost:8080就能够访问到其路径中相对应的资源;
其他机器用IP地址加上端口号也能够访问到同样的资源 比如 192.163.2.1:8080
当然在项目的开发当中,我们一般不会写服务器,通常我们项目中会用到tomcat服务器,在以后的博客中会有介绍。

猜你喜欢

转载自blog.csdn.net/Yin_Xian/article/details/52790960