Linux下的http服务器 v0.0.0.0.0.0.1

本文详细介绍了如何使用C++实现一个HTTP服务器,包括初始化参数、连接线程、主线程等关键步骤,并提供了运行示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码如下


http_server.cpp



/*
* compile: g++ -o http_server.out http_server.cpp -lpthread
* run: ./http_server.out
* before you run this programe ,you should have a file named "index.html" in your root directory
*/ 
#include <sys/socket.h>  
#include <sys/types.h>  
#include <poll.h>               
#include <unistd.h>          
#include <netdb.h>           
#include <error.h>           
#include <stdlib.h>  
#include <stdio.h>  
#include <errno.h>  
#include <string.h>  
#include <netdb.h>  
#include <netinet/in.h>  
#include <arpa/inet.h> 
#include <pthread.h> 


#define HTTP_SERVRE_PORT 80  //http server port  
#define BUFFSIZE 1024        // integer 1 stands for ture : running   
#define LISTENQ 10              
  
void http_response( int new_fd, char *request )
{
	char *token = strtok( request, " " ); //token is the name of the method 
	char *uri = strtok( NULL, " " );      //the file you want to get
    
    char file[64];
	sprintf( file, ".%s", uri );

	{
		FILE *fp = fopen( file, "rb" );
		if( fp == 0 )
		{
			char response[] = "HTTP/1.1 404 NOT FOUND\r\n\r\n";
			write(new_fd,response,strlen(response));
			
		}
		else
		{
			int file_size ;
			char *content;
			char response[1024];
			fseek( fp, 0, SEEK_END );//to the end of the file  
			file_size = ftell( fp ); //get file size
			fseek( fp, 0, SEEK_SET );//to the beginning of the file
			content = (char*)malloc( file_size + 1 );
			fread( content, file_size, 1, fp );
			content[file_size] = 0;
			sprintf( response, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: %d\r\n\r\n%s", file_size, content );
			write(new_fd,response,strlen(response));
			free( content );
		}
	}
}

int sockfd;  
struct sockaddr_in server_addr;  
struct sockaddr_in client_addr;  

//init param of the http server 

bool initialize_server()
{
    //socket  
  
    if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)  
    {  
            fprintf(stderr,"Socket error:%s\n\a",strerror(errno));  
            exit(1);  
    }  

    bzero(&server_addr,sizeof(struct sockaddr_in));  
    server_addr.sin_family=AF_INET;  
    server_addr.sin_addr.s_addr=htonl(INADDR_ANY);  
    server_addr.sin_port=htons(HTTP_SERVRE_PORT);  

    //bind  

    if(bind(sockfd,(struct sockaddr *)(&server_addr),sizeof(struct sockaddr))== -1)  
    {  
            fprintf(stderr,"Bind error:%s\n\a",strerror(errno));  
            exit(1);  
    }  

    //listen  

    if(listen(sockfd,LISTENQ)==-1)  
    {  
            fprintf(stderr,"Listen error:%s\n\a",strerror(errno));  
            exit(1);  
    }  
}

//connection thread

void * connection_thread(void * arg)
{ 
    pthread_detach(pthread_self());//回制定线程结束时回收资源 
    int new_fd = *(int *)arg;
    int nbytes;  
    char request[BUFFSIZE];  
    if((nbytes=read(new_fd,request,BUFFSIZE))==-1)  
    {  
            fprintf(stderr,"Read Error:%s\n",strerror(errno));  
            exit(1);  
    }  
    request[nbytes]='\0';  
    
    printf("new_fd: %d\n",new_fd);
    printf("Request From Client (%s:%d):\ncontent of char * request[] is :\n%s\n",inet_ntoa(client_addr.sin_addr),client_addr.sin_port,request);  
    http_response(new_fd, request );
     
    close(new_fd); 
    pthread_exit(0);  
}


//main thread

void httpserver_start_work()
{
     unsigned int sin_size; 
     while(1)  
    {  
            //accept  
            int new_fd;
            sin_size=sizeof(struct sockaddr_in);  
            if((new_fd=accept(sockfd,(struct sockaddr *)(&client_addr),&sin_size))==-1)  
            {  
                    fprintf(stderr,"Accept error:%s\n\a",strerror(errno));  
                    exit(1);  
            }  

            //recv  
            
            pthread_t tid;
            //create a new thread to serve each request
            pthread_create(&tid, NULL, connection_thread, &new_fd);
            
            

    }  
    close(sockfd);  
}


int main()
{

    //init param of the http server 
    initialize_server();
    //main thread
    httpserver_start_work();
    
	return 0;
}


type http://your-hostname/index.html in your web browser the click enter 


you will see this;



. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v3.1.3) 2025-03-24T10:17:43.954+08:00 INFO 1 --- [ main] c.xymzsfxy.backend.BackendApplication : Starting BackendApplication v0.0.1-SNAPSHOT using Java 17 with PID 1 (/usr/local/java/backend.jar started by root in /usr/local/java) 2025-03-24T10:17:43.965+08:00 INFO 1 --- [ main] c.xymzsfxy.backend.BackendApplication : No active profile set, falling back to 1 default profile: "default" 2025-03-24T10:17:49.146+08:00 INFO 1 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode. 2025-03-24T10:17:49.449+08:00 INFO 1 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 263 ms. Found 2 JPA repository interfaces. 2025-03-24T10:17:52.322+08:00 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) 2025-03-24T10:17:52.384+08:00 INFO 1 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2025-03-24T10:17:52.385+08:00 INFO 1 --- [ main] o.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/10.1.12] 2025-03-24T10:17:52.715+08:00 INFO 1 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2025-03-24T10:17:52.721+08:00 INFO 1 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 8381 ms 2025-03-24T10:17:53.346+08:00 INFO 1 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default] 2025-03-24T10:17:53.585+08:00 INFO 1 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 6.2.7.Final 2025-03-24T10:17:53.593+08:00 INFO 1 --- [ main] org.hibernate.cfg.Environment : HHH000406: Using bytecode reflection optimizer 2025-03-24T10:17:54.282+08:00 INFO 1 --- [ main] o.h.b.i.BytecodeProviderInitiator : HHH000021: Bytecode provider name : bytebuddy 2025-03-24T10:17:54.946+08:00 INFO 1 --- [ main] o.s.o.j.p.SpringPersistenceUnitInfo : No LoadTimeWeaver setup: ignoring JPA class transformer [root@iZ2ze3k6buohug6id3eg97Z java]#怎么访问接口数据
最新发布
03-25
<think>嗯,用户的问题是关于如何访问一个Spring Boot应用的接口数据。首先,我需要分析用户提供的日志信息。看起来用户已经成功启动了Spring Boot应用,版本是v3.1.3,使用Java 17,应用在8080端口上运行。日志显示应用正常启动,没有明显的错误。 用户现在想知道如何访问接口数据,可能意味着他们部署了应用,但不知道如何测试或使用提供的API。需要分步骤指导他们如何访问这些接口。 首先,确定应用运行的主机和端口。根据日志,Tomcat在8080端口启动,所以默认情况下接口地址应该是http://服务器IP:8080/端点路径。如果应用在本地运行,可能用localhost,如果在远程服务器,则需要服务器的公网IP或域名。 然后,需要确认应用有哪些暴露的接口。用户可能需要检查他们的控制器类,查看是否有@RequestMapping或@GetMapping等注解定义的路径。例如,如果有@RestController的类,里面有一个@GetMapping("/hello")的方法,那么访问的URL就是http://localhost:8080/hello。 接下来,用户可能需要使用工具来测试接口,比如curl、Postman,或者浏览器直接访问。如果是GET请求,浏览器可以直接访问。对于POST或其他方法,可能需要Postman。此外,检查应用是否配置了安全设置,比如Spring Security,可能导致接口需要认证,这时候用户需要提供token或者禁用安全配置。 另外,查看应用的配置文件,比如application.properties或application.yml,确认是否有自定义的上下文路径,比如server.servlet.context-path=/api,这样接口的URL会变成http://localhost:8080/api/端点。 用户可能遇到的问题包括防火墙设置没有开放8080端口,导致无法远程访问。需要检查服务器的安全组规则或iptables配置。此外,应用可能只在本地回环地址上监听,需要确保服务器绑定到0.0.0.0。 最后,可能需要查看日志确认接口是否注册成功。Spring Boot启动时通常会列出所有映射的端点,或者在actuator的/actuator/mappings端点查看,但需要确保actuator依赖已添加并且暴露了该端点。 总结起来,步骤应该是:确认接口地址和端口,检查接口定义,使用工具测试,处理可能的网络或安全配置问题,查看日志或actuator端点确认接口是否存在。</think>以下是访问Spring Boot接口数据的步骤分析: ===================== 一、确认基础信息 ===================== 1. 根据日志显示: - 应用端口:$8080$(Tomcat initialized with port(s): 8080) - 启动时间:$2025-03-24T10:17:43.954+08:00$(实际应关注当前时间) - Java版本:$17$ 2. 访问地址公式: $$http://[服务器IP]:8080/[接口路径]$$ - 本地测试使用:$http://localhost:8080$ - 服务器部署使用公网IP ===================== 二、确定接口路径 ===================== 1. 检查控制器代码示例: ```java @RestController public class DemoController { @GetMapping("/api/data") public ResponseEntity<?> getData() { // 业务逻辑 } } ``` 对应访问路径:$http://localhost:8080/api/data$ 2. 查看启动日志中的映射记录: ``` 2025-03-24T10:17:52.XXX INFO o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/api/**] ``` ===================== 三、访问方式示例 ===================== 1. 浏览器直接访问(GET请求): ```bash # Linux服务器本地访问 curl http://localhost:8080/api/data # 外网访问(需开放安全组) curl http://公网IP:8080/api/data ``` 2. Postman测试: - Method选择对应类型(GET/POST/PUT等) - Headers添加: $$Content-Type: application/json$$ ===================== 四、常见问题排查 ===================== 1. 网络连通性验证: ```bash telnet 服务器IP 8080 # 或 nc -zv 服务器IP 8080 ``` 2. Spring Security配置检查: ```java @Configuration @EnableWebSecurity public class SecurityConfig { @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(auth -> auth .requestMatchers("/api/**").permitAll() // 必须开放接口路径 ); return http.build(); } } ``` 3. 查看完整接口列表(需actuator依赖): ```properties # application.properties management.endpoints.web.exposure.include=* management.endpoint.health.show-details=always ``` 访问路径:$http://localhost:8080/actuator/mappings$ ===================== 五、高级调试技巧 ===================== 1. 启用Swagger文档: 添加依赖: ```xml <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <version>2.1.0</version> </dependency> ``` 访问路径:$http://localhost:8080/swagger-ui/index.html$ 2. 实时日志监控: ```bash tail -f /var/log/spring-app.log ``` > 注意:如果部署在Docker容器中,需确保端口映射正确: > ```dockerfile > EXPOSE 8080 > ``` > 启动命令应包含端口映射: > ```bash > docker run -p 8080:8080 your-image > ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值