Ошибка java.net.SocketException: Conection reset – как исправить
Сразу сообщу, что если у вас проблема с игрой майнкрафт, то листайте в самый конец статьи, а пока информация для разработчиков и программистов.
В этом примере мы поговорим о java.net.SocketException. Это подкласс IOException, поэтому это проверенное исключение, которое сигнализирует о проблеме при попытке открыть или получить доступ к сокету.
Настоятельно рекомендуется использовать самый «определенный» класс исключений сокетов, который более точно определяет проблему. Стоит также отметить, что SocketException, выдаётся на экран с сообщением об ошибке, которое очень информативно описывает ситуацию, вызвавшую исключение.
Простое клиент-серверное приложение
Чтобы продемонстрировать это исключение, я собираюсь позаимствовать некоторый код из клиент-серверного приложения, которое есть в java.net.ConnectException. Он состоит из 2 потоков.
Получается, что 2 потока будут в разных классах, запущенных двумя разными основными методами, чтобы вызвать исключение:
Как вы можете видеть, я поместил в SimpleClient 15-секундную задержку, прежде чем попытаться отправить свое сообщение. К тому моменту, когда клиент вызывает sleep(), он уже создал соединение с сервером. Я собираюсь запустить оба потока, и после того, как клиент установит соединение, я внезапно остановлю клиентское приложение.
Вот что происходит на стороне сервера:
Мы получаем исключение SocketException с сообщением «Сброс подключения». Это происходит, когда один из участников принудительно закрывает соединение без использования close().
Конечно, вы можете сделать оперативное закрытие соединения, не закрывая приложение вручную. В коде клиента, после ожидания в течение 15 секунд (или меньше), вы можете выдать новое исключение (используя throws new Exception ()), но вы должны удалить finally, иначе соединение будет нормально закрываться, и SocketException не будет сброшен.
Как решить проблему с SocketException
SocketException – это общее исключение, обозначающее проблему при попытке доступа или открытия Socket. Решение этой проблемы должно быть сделано с особой тщательностью. Вы должны всегда регистрировать сообщение об ошибке, которое сопровождает исключение.
В предыдущем примере мы видели код сообщения. Это происходит, когда один из участников принудительно закрывает соединение без использования close(). Это означает, что вы должны проверить, был ли один из участников неожиданно прерван.
Также может быть сообщение «Слишком много открытых файлов», особенно если вы работаете в Linux. Это сообщение обозначает, что многие файловые дескрипторы открыты для системы. Вы можете избежать этой ошибки, если перейдете в /etc/sysctl.conf и увеличите число в поле fs.file-max. Или попытаться выделить больше стековой памяти.
Конечно, можно встретить много других сообщений. Например, «Ошибка привязки», где ваше соединение не может быть установлено, поскольку порт не может быть привязан к сокету. В этом случае проверьте, используется ли порт и т. д.
Если у вас проблема с minecraft, то чтобы решить проблему попробуйте сделать следующее:
Средняя оценка / 5. Количество голосов:
java.net.SocketException: Network is unreachable: connect
I am trying to download a xml text file from a web server using this method:
Sometimes this exception is thrown (where I specified is code):
6 Answers 6
You are facing a connection breakdown. Does this happen in 3G, WiFi or «plain» connection on a computer?
Anyway, you must assume that the connection may be lost from time to time, when writing your app. For example, with mobiles, this happens frequently in the tube, in basements, etc. With PC apps, this is less frequent but occurs sometimes.
A retry can be a good solution. And a clean error message that explains the network is not available at this moment too.
«Network is unreachable» means just that. You’re not connected to a network. It’s something outside of your program. Could be a bad OS setting, NIC, router, etc.
I haven’t tested with your code so it would be totally different case though, still I’d like to share my experience. (Also this must be too late answer though, I hope this answer still would help somebody in the future)
I recently faced similar experience like you such as some times Network is unreachable, but sometimes not. In short words, what was cause is too small time out. It seems Java throws IOException with stating «Network is unreachable» when the connection fails because of it. It was so misleading (I would expect something like saying «time out») and I spent almost a month to detect it.
Here I found another post about how to set time out. Alternative to java.net.URL for custom timeout setting
Again, this might not the same case as you got experienced, but somebody for the future.
Minecraft Forums
java.net.SocketExecption: Network is unreachable
I have a server running on a Mac using Craftbukkit. Recently, my computer’s graphics card had to be replaced; and ever since, my friends could not connect to the server. Only I can, using «localhost». When anybody else tries to connect, they get the following error message: «Failed to connect to the server java.net.SocketExecption: Network is unreachable».
Please help! Btw, I tried restarting the server, my wireless connection, and even my computer; yet still nothing works.
This strongly implies that the IP address they are trying to use is bogus.
A port forwarding problem would not manifest itself as a NETWORK unreachable.
This message means that an IP router somewhere is throwing up it’s hands and saying «I have no idea where to send this»
This strongly implies that the IP address they are trying to use is bogus.
A port forwarding problem would not manifest itself as a NETWORK unreachable.
This message means that an IP router somewhere is throwing up it’s hands and saying «I have no idea where to send this»
The odd thing is that they have been using the same IP all the time, and only now am I getting this error. I got the IP to use off of IPChicken, and it is the same as always.
that error means the device where your packets are arriving is NOT LISTENING.
So.. either your server is not running, or you are using the wrong IP address to connect with, or your port forwarding is pointed at the wrong IP address.
This is not usually a firewall issue, as they usually just silently eat packets.
that error means the device where your packets are arriving is NOT LISTENING.
So.. either your server is not running, or you are using the wrong IP address to connect with, or your port forwarding is pointed at the wrong IP address.
This is not usually a firewall issue, as they usually just silently eat packets.
My server is running, I use the right IP, and I’m pretty sure my port forwarding is pointed at the correct IP address. Whenever I go on Verizon and port forward, it seems to work; yet when I go on canyouseeme.org and test port 25565, it also says connection refused. Man, is this annoying.
EDIT: Other computers in my LAN can connect to my server, but still not outside of my LAN.
java net socketexception network is unreachable
Очередь просмотра
Очередь
YouTube Premium
Хотите сохраните это видео?
Пожаловаться на видео?
Выполните вход, чтобы сообщить о неприемлемом контенте.
Понравилось?
Не понравилось?
Текст видео
If you guys enjoy make sure to sub and like also share this video because a lot of people are have this problem.
Preferred DNS sever:208.67.222.222
Alternate DNS sever:208.67.220.220
This worked for me so hope it works for you also.
I am trying to download a xml text file from a web server using this method:
Sometimes this exception is thrown (where I specified is code):
4 Answers 4
You are facing a connection breakdown. Does this happen in 3G, WiFi or «plain» connection on a computer?
Anyway, you must assume that the connection may be lost from time to time, when writing your app. For example, with mobiles, this happens frequently in the tube, in basements, etc. With PC apps, this is less frequent but occurs sometimes.
A retry can be a good solution. And a clean error message that explains the network is not available at this moment too.
«Network is unreachable» means just that. You’re not connected to a network. It’s something outside of your program. Could be a bad OS setting, NIC, router, etc.
I haven’t tested with your code so it would be totally different case though, still I’d like to share my experience. (Also this must be too late answer though, I hope this answer still would help somebody in the future)
I recently faced similar experience like you such as some times Network is unreachable, but sometimes not. In short words, what was cause is too small time out. It seems Java throws IOException with stating «Network is unreachable» when the connection fails because of it. It was so misleading (I would expect something like saying «time out») and I spent almost a month to detect it.
Here I found another post about how to set time out. Alternative to java.net.URL for custom timeout setting
Again, this might not the same case as you got experienced, but somebody for the future.
Comments
Copy link Quote reply
marbetschar commented Oct 18, 2016 •
For some reason I receive the above error on the production machine (Linux). Strange thing is, on my dev machine — which is a windows system — there is no such error while using the exact same connection information.
Even more odd after several retries it just starts working, till the next time this code should be executed a few minutes later; then it needs again several retries to run properly.
Please note the code runs as a daemon within an endless loop, which sleeps several minutes between the different executions.
This comment has been minimized.
Copy link Quote reply
marbetschar commented Oct 18, 2016 •
Ok; it seems to be a regular networking issue. If I try to telnet autodiscover.domain.tld 443 I got the following errors on the Linux server:
This comment has been minimized.
Copy link Quote reply
PranamBhat commented Jul 19, 2019
Whenever I run my application, I’m getting the connection request failure exception. The application tries to hit the URL and end up with connection failure.
I have tried the same on Postman. It is giving me 200: OK.
I have the proxy and port as well. How to use it in our spring boot application. Whenever the application runs it should take the respective proxy and port.
Minecraft Forums
java.netSocketException: Network is unreachable
When I try to connect to my server using my EXTERNAL IP, I get the following message:
Failed to connect to the server
java.net.SocketException: Network is unreachable.
How do I fix this?
Oh yeah, I’m on a Mac.
I’m pretty sure my NAT is moderate.
I cannot see the port 25565. Port forwarding really isn’t all that hard though, you just enter the name (Minecraft), the starting port (25565), the ending port (25565), the type (TCP/UDP or whatever it is) and the server IP which I entered correctly. I know it is correct because I have watched a lot of tutorials.
I’m pretty sure my NAT is moderate.
I cannot see the port 25565. Port forwarding really isn’t all that hard though, you just enter the name (Minecraft), the starting port (25565), the ending port (25565), the type (TCP/UDP or whatever it is) and the server IP which I entered correctly. I know it is correct because I have watched a lot of tutorials.
If the port is not showing as «OPEN» on that site, then it is not open to people who are outside of your network. Simply putting in a port is not port forwarding, you need to explicitly tell your router what port to send where.
Edit: Misread your post. If you set up the forwarding, make sure your server is not firewalled, etc..
I am on a Mac with the latest OSX, Snow Leopard or whatever. I have tried port forwarding from the main computer on the network, but it didn’t help. The firewall is currently not running on my Mac, and never has. I think the Firewall is most likely on the router, but I’m not certain. The main computer on the network is running Windows XP.
I am on a Mac with the latest OSX, Snow Leopard or whatever. I have tried port forwarding from the main computer on the network, but it didn’t help. The firewall is currently not running on my Mac, and never has. I think the Firewall is most likely on the router, but I’m not certain. The main computer on the network is running Windows XP.
Depending on the type of router you have (would be helpful info as well), you would likely find the firewall setting in the security or administration section. However, port forwarding usually adds a rule to the firewall which would make it a non-issue in most cases.





