启用Tomcat时,报异常:failed to connect to localhost/127.0.0.1 (port 8080)

本文针对出现的java.net.ConnectException异常,提供了详细的解决方案。通过将localhost替换为实际的IP地址,可以有效解决连接被拒绝的问题,并给出了修改后的示例代码。

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

异常如下:

java.net.ConnectException: failed to connect to localhost/127.0.0.1 (port 8080) after 8000ms: isConnected failed: ECONNREFUSED (Connection refused)


解决方法:

如果url是:localhost:8080 或 127.0.0.1:8080

则应替换 localhost/127.0.0.1 处为本机的ip地址,查询本机ip地址可打开cdm输入 ipconfig 命令,在“IPv4地址”后即是(Mac打开终端输入 ifconfig | grep "inet " | grep -v 127.0.0.1 


示例如下:

URL url = new URL("http://192.168.1.105:8080/*");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setRequestMethod("GET");
connection.setConnectTimeout(8 * 1000);
connection.setReadTimeout(8 * 1000);
connection.setDoInput(true);
connection.setDoOutput(true);
InputStream in = connection.getInputStream();

BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
    response.append(line);
}



root@ecm-e00f:/yunxiang/data/nacos/conf# cat application.properties # # Copyright 1999-2021 Alibaba Group Holding Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # #*************** Spring Boot Related Configurations ***************# ### Default web context path: server.servlet.contextPath=/nacos ### Include message field server.error.include-message=ALWAYS ### Default web server port: server.port=8848 #*************** Network Related Configurations ***************# ### If prefer hostname over ip for Nacos server addresses in cluster.conf: # nacos.inetutils.prefer-hostname-over-ip=false ### Specify local server's IP: # nacos.inetutils.ip-address= #*************** Config Module Related Configurations ***************# ### If use MySQL as datasource: ### Deprecated configuration property, it is recommended to use `spring.sql.init.platform` replaced. spring.datasource.platform=mariadb # spring.sql.init.platform=mysql ### Count of DB: db.num=1 ### Connect URL of DB: db.url.0=jdbc:mariadb://127.0.0.1:3306/transport_config?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&useSSL=false db.user.0=transport_config_user db.password.0=Yx_sec_Db@911^38 db.driver.0=org.mariadb.jdbc.Driver #db.url.0=jdbc:mariadb://127.0.0.1:3306/transport_config?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=false&characterEncoding=utf8 #db.user.0=transport_config_user #db.password.0=Yx_sec_Db@911^38 ### Connection pool configuration: hikariCP db.pool.config.connectionTimeout=30000 db.pool.config.validationTimeout=10000 db.pool.config.maximumPoolSize=20 db.pool.config.minimumIdle=2 ### the maximum retry times for push nacos.config.push.maxRetryTime=50 #*************** Naming Module Related Configurations ***************# ### If enable data warmup. If set to false, the server would accept request without local data preparation: # nacos.naming.data.warmup=true ### If enable the instance auto expiration, kind like of health check of instance: # nacos.naming.expireInstance=true nacos.naming.empty-service.auto-clean=true nacos.naming.empty-service.clean.initial-delay-ms=50000 nacos.naming.empty-service.clean.period-time-ms=30000 ### Add in 2.0.0 ### The interval to clean empty service, unit: milliseconds. # nacos.naming.clean.empty-service.interval=60000 ### The expired time to clean empty service, unit: milliseconds. # nacos.naming.clean.empty-service.expired-time=60000 ### The interval to clean expired metadata, unit: milliseconds. # nacos.naming.clean.expired-metadata.interval=5000 ### The expired time to clean metadata, unit: milliseconds. # nacos.naming.clean.expired-metadata.expired-time=60000 ### The delay time before push task to execute from service changed, unit: milliseconds. # nacos.naming.push.pushTaskDelay=500 ### The timeout for push task execute, unit: milliseconds. # nacos.naming.push.pushTaskTimeout=5000 ### The delay time for retrying failed push task, unit: milliseconds. # nacos.naming.push.pushTaskRetryDelay=1000 ### Since 2.0.3 ### The expired time for inactive client, unit: milliseconds. # nacos.naming.client.expired.time=180000 #*************** CMDB Module Related Configurations ***************# ### The interval to dump external CMDB in seconds: # nacos.cmdb.dumpTaskInterval=3600 ### The interval of polling data change event in seconds: # nacos.cmdb.eventTaskInterval=10 ### The interval of loading labels in seconds: # nacos.cmdb.labelTaskInterval=300 ### If turn on data loading task: # nacos.cmdb.loadDataAtStart=false #***********Metrics for tomcat **************************# server.tomcat.mbeanregistry.enabled=true #***********Expose prometheus and health **************************# #management.endpoints.web.exposure.include=prometheus,health ### Metrics for elastic search management.metrics.export.elastic.enabled=false #management.metrics.export.elastic.host=http://localhost:9200 ### Metrics for influx management.metrics.export.influx.enabled=false #management.metrics.export.influx.db=springboot #management.metrics.export.influx.uri=http://localhost:8086 #management.metrics.export.influx.auto-create-db=true #management.metrics.export.influx.consistency=one #management.metrics.export.influx.compressed=true #*************** Access Log Related Configurations ***************# ### If turn on the access log: server.tomcat.accesslog.enabled=true ### file name pattern, one file per hour server.tomcat.accesslog.rotate=true server.tomcat.accesslog.file-date-format=.yyyy-MM-dd-HH ### The access log pattern: server.tomcat.accesslog.pattern=%h %l %u %t "%r" %s %b %D %{User-Agent}i %{Request-Source}i ### The directory of access log: server.tomcat.basedir=file:. #*************** Access Control Related Configurations ***************# ### If enable spring security, this option is deprecated in 1.2.0: #spring.security.enabled=false ### The ignore urls of auth nacos.security.ignore.urls=/,/error,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-ui/public/**,/v1/auth/**,/v1/console/health/**,/actuator/**,/v1/console/server/** ### The auth system to use, currently only 'nacos' and 'ldap' is supported: nacos.core.auth.system.type=nacos ### If turn on auth system: nacos.core.auth.enabled=false ### Turn on/off caching of auth information. By turning on this switch, the update of auth information would have a 15 seconds delay. nacos.core.auth.caching.enabled=true ### Since 1.4.1, Turn on/off white auth for user-agent: nacos-server, only for upgrade from old version. nacos.core.auth.enable.userAgentAuthWhite=false ### Since 1.4.1, worked when nacos.core.auth.enabled=true and nacos.core.auth.enable.userAgentAuthWhite=false. ### The two properties is the white list for auth and used by identity the request from other server. nacos.core.auth.server.identity.key= nacos.core.auth.server.identity.value= ### worked when nacos.core.auth.system.type=nacos ### The token expiration in seconds: nacos.core.auth.plugin.nacos.token.cache.enable=false nacos.core.auth.plugin.nacos.token.expire.seconds=18000 ### The default token (Base64 String): nacos.core.auth.plugin.nacos.token.secret.key= ### worked when nacos.core.auth.system.type=ldap,{0} is Placeholder,replace login username #nacos.core.auth.ldap.url=ldap://localhost:389 #nacos.core.auth.ldap.basedc=dc=example,dc=org #nacos.core.auth.ldap.userDn=cn=admin,${nacos.core.auth.ldap.basedc} #nacos.core.auth.ldap.password=admin #nacos.core.auth.ldap.userdn=cn={0},dc=example,dc=org #nacos.core.auth.ldap.filter.prefix=uid #nacos.core.auth.ldap.case.sensitive=true #nacos.core.auth.ldap.ignore.partial.result.exception=false #*************** Control Plugin Related Configurations ***************# # plugin type #nacos.plugin.control.manager.type=nacos # local control rule storage dir, default ${nacos.home}/data/connection and ${nacos.home}/data/tps #nacos.plugin.control.rule.local.basedir=${nacos.home} # external control rule storage type, if exist #nacos.plugin.control.rule.external.storage= #*************** Config Change Plugin Related Configurations ***************# # webhook #nacos.core.config.plugin.webhook.enabled=false # It is recommended to use EB https://help.aliyun.com/document_detail/413974.html #nacos.core.config.plugin.webhook.url=http://localhost:8080/webhook/send?token=*** # The content push max capacity ,byte #nacos.core.config.plugin.webhook.contentMaxCapacity=102400 # whitelist #nacos.core.config.plugin.whitelist.enabled=false # The import file suffixs #nacos.core.config.plugin.whitelist.suffixs=xml,text,properties,yaml,html # fileformatcheck,which validate the import file of type and content #nacos.core.config.plugin.fileformatcheck.enabled=false #*************** Istio Related Configurations ***************# ### If turn on the MCP server: nacos.istio.mcp.server.enabled=false #*************** Core Related Configurations ***************# ### set the WorkerID manually # nacos.core.snowflake.worker-id= ### Member-MetaData # nacos.core.member.meta.site= # nacos.core.member.meta.adweight= # nacos.core.member.meta.weight= ### MemberLookup ### Addressing pattern category, If set, the priority is highest # nacos.core.member.lookup.type=[file,address-server] ## Set the cluster list with a configuration file or command-line argument # nacos.member.list=192.168.16.101:8847?raft_port=8807,192.168.16.101?raft_port=8808,192.168.16.101:8849?raft_port=8809 ## for AddressServerMemberLookup # Maximum number of retries to query the address server upon initialization # nacos.core.address-server.retry=5 ## Server domain name address of [address-server] mode # address.server.domain=jmenv.tbsite.net ## Server port of [address-server] mode # address.server.port=8080 ## Request address of [address-server] mode # address.server.url=/nacos/serverlist #*************** JRaft Related Configurations ***************# ### Sets the Raft cluster election timeout, default value is 5 second # nacos.core.protocol.raft.data.election_timeout_ms=5000 ### Sets the amount of time the Raft snapshot will execute periodically, default is 30 minute # nacos.core.protocol.raft.data.snapshot_interval_secs=30 ### raft internal worker threads # nacos.core.protocol.raft.data.core_thread_num=8 ### Number of threads required for raft business request processing # nacos.core.protocol.raft.data.cli_service_thread_num=4 ### raft linear read strategy. Safe linear reads are used by default, that is, the Leader tenure is confirmed by heartbeat # nacos.core.protocol.raft.data.read_index_type=ReadOnlySafe ### rpc request timeout, default 5 seconds # nacos.core.protocol.raft.data.rpc_request_timeout_ms=5000 #*************** Distro Related Configurations ***************# ### Distro data sync delay time, when sync task delayed, task will be merged for same data key. Default 1 second. # nacos.core.protocol.distro.data.sync.delayMs=1000 ### Distro data sync timeout for one sync data, default 3 seconds. # nacos.core.protocol.distro.data.sync.timeoutMs=3000 ### Distro data sync retry delay time when sync data failed or timeout, same behavior with delayMs, default 3 seconds. # nacos.core.protocol.distro.data.sync.retryDelayMs=3000 ### Distro data verify interval time, verify synced data whether expired for a interval. Default 5 seconds. # nacos.core.protocol.distro.data.verify.intervalMs=5000 ### Distro data verify timeout for one verify, default 3 seconds. # nacos.core.protocol.distro.data.verify.timeoutMs=3000 ### Distro data load retry delay when load snapshot data failed, default 30 seconds. # nacos.core.protocol.distro.data.load.retryDelayMs=30000 ### enable to support prometheus service discovery #nacos.prometheus.metrics.enabled=true ### Since 2.3 #*************** Grpc Configurations ***************# ## sdk grpc(between nacos server and client) configuration ## Sets the maximum message size allowed to be received on the server. #nacos.remote.server.grpc.sdk.max-inbound-message-size=10485760 ## Sets the time(milliseconds) without read activity before sending a keepalive ping. The typical default is two hours. #nacos.remote.server.grpc.sdk.keep-alive-time=7200000 ## Sets a time(milliseconds) waiting for read activity after sending a keepalive ping. Defaults to 20 seconds. #nacos.remote.server.grpc.sdk.keep-alive-timeout=20000 ## Sets a time(milliseconds) that specify the most aggressive keep-alive time clients are permitted to configure. The typical default is 5 minutes #nacos.remote.server.grpc.sdk.permit-keep-alive-time=300000 ## cluster grpc(inside the nacos server) configuration #nacos.remote.server.grpc.cluster.max-inbound-message-size=10485760 ## Sets the time(milliseconds) without read activity before sending a keepalive ping. The typical default is two hours. #nacos.remote.server.grpc.cluster.keep-alive-time=7200000 ## Sets a time(milliseconds) waiting for read activity after sending a keepalive ping. Defaults to 20 seconds. #nacos.remote.server.grpc.cluster.keep-alive-timeout=20000 ## Sets a time(milliseconds) that specify the most aggressive keep-alive time clients are permitted to configure. The typical default is 5 minutes #nacos.remote.server.grpc.cluster.permit-keep-alive-time=300000 ## open nacos default console ui #nacos.console.ui.enabled=true
07-08
<think>好的,用户遇到了连接到本地服务器端口6400被拒绝的问题。首先,我需要确定这个端口是否被正确配置并且服务正在运行。用户可能是在尝试访问某个本地服务,比如数据库、API服务器或其他应用程序,但连接被拒绝通常意味着服务没有运行或者端口被防火墙阻止。 接下来,我应该考虑常见的故障原因。首先是服务是否真的在运行。用户可能没有启动对应的服务,或者服务启动失败。其次是端口是否正确,是否有拼写错误,比如端口号是否正确配置为6400。第三是防火墙或安全软件是否阻止了该端口的连接,这可能需要检查系统防火墙设置或第三方安全软件的规则。 另外,用户可能是在开发环境中使用localhost,但服务绑定的IP地址可能不是127.0.0.1,比如绑定到了0.0.0.0或者特定的网络接口,导致无法通过127.0.0.1访问。此外,网络配置问题,比如本地网络栈异常,也可能导致连接问题。 需要指导用户逐步排查这些问题。首先确认服务状态,检查是否启动成功。然后检查端口监听情况,使用netstat或ss命令查看端口是否被服务占用。接着检查防火墙规则,确保端口开放。最后,验证服务配置,确认绑定的IP和端口是否正确。 可能还需要考虑其他可能性,比如服务依赖的其他组件是否正常运行,或者是否有资源不足导致服务崩溃。用户可能需要查看服务日志,寻找启动错误或运行异常的信息。 最后,总结可能的解决步骤,提供清晰的指令,帮助用户逐步排除故障,并确保他们能够验证每一步的结果。同,准备相关问题,帮助用户进一步深入排查或扩展解决方案。</think>根据您遇到的`Connection refused: getsockopt`错误,问题出在**无法连接到本地6400端口服务**。以下是完整的排查与解决方案: --- ### 🔍 故障定位流程 1. **确认服务状态**:检查目标服务是否已启动 2. **验证端口监听**:确认6400端口是否被正确绑定 3. **检查防火墙规则**:排查本地防火墙/安全软件拦截 4. **网络配置验证**:确保服务绑定地址为`0.0.0.0`或`127.0.0.1` --- ### ✅ 修复步骤(按顺序执行) #### 1. **确认服务是否运行** ```bash # Linux/macOS ps aux | grep 6400 # Windows tasklist | findstr :6400 ``` 如果未看到对应进程,说明服务未启动。请手动启动服务: ```bash # 示例(根据您的实际服务路径调整) ./your-service --port=6400 ``` #### 2. **检查端口监听状态** ```bash # Linux/macOS sudo netstat -tuln | grep 6400 # Windows netstat -ano | findstr :6400 ``` 预期输出应包含: ``` tcp6 0 0 :::6400 :::* LISTEN ``` 如果没有输出,说明服务未绑定端口。 #### 3. **验证服务绑定地址** 修改服务配置文件或启动参数,确保绑定地址为`0.0.0.0`(而非`127.0.0.1`): ```yaml # 示例配置文件 server: host: 0.0.0.0 port: 6400 ``` #### 4. **检查防火墙规则** ```bash # Linux sudo ufw status | grep 6400 # macOS sudo pfctl -s rules | grep 6400 # Windows netsh advfirewall firewall show rule name=all | findstr :6400 ``` 若发现拦截规则,临关闭防火墙测试: ```bash # Linux sudo ufw disable # Windows netsh advfirewall set allprofiles state off ``` #### 5. **测试本地环回连接** 使用`curl`直接测试本地访问: ```bash curl -v http://127.0.0.1:6400 ``` 如果失败,说明服务本身存在问题。 --- ### 🛠️ 常见场景修复方案 #### 场景1:服务未启动 - **现象**:`netstat`无监听,`ps`无进程 - **解决**: ```bash # 启动服务(示例) nohup your-service --port=6400 > service.log 2>&1 & # 查看启动日志 tail -f service.log ``` #### 场景2:端口被占用 - **现象**:`Address already in use`错误 - **解决**: ```bash # 查找占用进程 lsof -i :6400 # 终止冲突进程(谨慎操作) kill -9 <PID> ``` #### 场景3:服务崩溃 - **现象**:服务启动后立即退出 - **解决**: 1. 检查核心转储文件(如有) 2. 增加内存限制: ```bash ulimit -n 65536 # 提高文件描述符限制 ``` --- ### 📌 高级调试技巧 1. **使用`tcpdump`抓包验证请求是否到达**: ```bash sudo tcpdump -i lo -nn port 6400 ``` 2. **检查系统日志**: ```bash dmesg | grep -i kill # 查看OOM Killer是否触发 journalctl -u your-service # systemd服务日志 ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值