I want to transfer some data between PC and a mobile phone with WiFi.
This is how I get the WiFi IP address:
String ip = String.format( "%d.%d.%d.%d", (wifiInfo.getIpAddress() & 0xff), (wifiInfo.getIpAddress() >> 8 & 0xff), (wifiInfo.getIpAddress() >> 16 & 0xff), (wifiInfo.getIpAddress() >> 24 & 0xff)); new Recive().execute(ip);
This is the code about sending a message to the PC:
Socket socket = null; String message = "test\r\n"; protected Void doInBackground(String... urls) { try { Log.i("ip", urls[0]); socket = new Socket(urls[0], 2468); toserver = new DataOutputStream(socket.getOutputStream()); toserver.writeBytes(message); toserver.flush(); toserver.close(); socket.close(); return null; } catch (Exception e) { Log.i("e", e.toString()); return null; } }
But an error occurs,
java.net.ConnectException: failed to connect to /192.168.253.3 (port 2468): connect failed: ECONNREFUSED (Connection refused)
Besides, I use a android phone to run the app.
net. ConnectException: Connection refused: 1) First try to ping the destination host, if the host is ping-able it means the client and server machine are in the network. 2) Try connecting to server host and port using telnet.
Connection refused is a clear case of a client trying to connect on a TCP port but not able to succeed. Below are some of the possible reason why java.net.ConnectException: Connection refused comes: 1) Client and Server, either or both of them are not in the network. 2) Server is not running.
Class ConnectException Signals that an error occurred while attempting to connect a socket to a remote address and port. Typically, the connection was refused remotely (e.g., no process is listening on the remote address/port).
A connect failed: ECONNREFUSED (Connection refused)
most likely means that there is nothing listening on that port AND that IP address. Possible explanations include:
Note that while you have an array variable called urls
, it cannot contain real URLs. There is no overload of the Socket
constructor that takes a real URL in any form. Indeed, if you supplied a URL in string form like this:
new Socket("http://example.com", 42)
the result would be a different exception. Likewise, if you attempt to connect to an IP address on a network that you can't route to (e.g. "a different WiFi network"), then you will get a different exception; e.g. "host not found", "no route to host" or "no route to network".
A common mistake during development of an android app running on a Virtual Device on your dev machine is to forget that the virtual device is not the same host as your dev machine. So if your server is running on your dev machine you cannot use a "http://localhost/..." url as that will look for the server endpoint on the virtual device not your dev machine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With