Android socket connection refused error - android

I want to implement socket connection between 2 deceives , client keep sending GPS data to the server and I need both of it run in new thread , the client send first one data then keep show error like this
03-18 16:35:11.805: E/Client run:(8163): java.net.ConnectException: failed to connect to /192.168.2.103 (port 5678): connect failed: ECONNREFUSED (Connection refused)
here is the client code
public class Send implements Runnable{
private boolean Connect = true;
public void Connect(){
Connect = true;
}
public void Disconnect(){
Connect = false;
}
#Override
public void run() {
// TODO Auto-generated method stub
while(Connect){
try {
SocketClient = new Socket("192.168.2.103", 5678);
ObjectOutputStream oos = new ObjectOutputStream(SocketClient.getOutputStream());
oos.writeDouble(GPSinfo[2]);
//ObjectInputStream ois = new ObjectInputStream(SocketClient.getInputStream());
//ois.readInt();
oos.close();
//ois.close();
} catch (Exception e) {
Log.e("Client run: ", e.toString());
}
}
}
}
here is server code
public class Receive implements Runnable{
private boolean CanReceive = true;
private double Data;
public void Connect(){
CanReceive = true;
}
public void Disconnect(){
CanReceive = false;
}
#Override
public void run() {
// TODO Auto-generated method stub
while(CanReceive){
try {
SocketServer = new ServerSocket(5678);
Socket connectedSocket = SocketServer.accept();
ObjectInputStream ois = new ObjectInputStream(connectedSocket.getInputStream());
Data = ois.readDouble();
DataText.setText("" + Data);
//ObjectOutputStream oos = new ObjectOutputStream(connectedSocket.getOutputStream());
//oos.writeInt(1);
//ois.close();
//oos.close();
} catch (Exception e) {
Log.e("Server run: ", e.toString());
}
}
}
}
by the way , the both code is inner class , and INTERNET permission is added.

It's obvious it's not a router-firewall related problem as you are under the same net, so there are only a few possibilities:
There's nothing listening on that port on that IP on the server-side
There's a local firewall on the server-side that is blocking that connection attempt
You are not using WIFI so you're not under the same net.
You should make sure you can open that service some ther way, that would help you debugging where the culprit is. If you've already done this, I'd suggest using some debugging tool to trace TCP packets (I don't know either what kind of operating system you use on the destination machine; if it's some linux distribution, tcpdump might help, in Win environments WireShark works just good).

This isn't a 'data transfer error'. This is a 'connection refused' error. It means the server you want to transfer the data to or from isn't running at the IP:port you specified.

Try killing the adb service before you begin the connection. I had a similar problem and killing the adb service before the connection resolved the issue.

I had the same error. I simply used ServerSocket and it worked well.
ServerSocket socket = new ServerSocket(8888);

Related

Impossible connecting to printer in thread

My problem is the next: I'm trying to print with my printer via wifi, I can print if I print a unique line. What I need is to create a kind of printer server which is listening requests to print all time in a loop, and through an arraylist with products what I want to print line by line. This is the code that I'm using:
for(FinalBarto barto : bartoProducts){
Product product = barto.getProducts();
MyPrinter printer = new MyPrinter(product,cxt);
printer.start();
}
And this is the class MyPrinter:
public class MyPrinter extends Thread {
Product producto;
Pack pack;
Context context;
Socket socket;
PrintWriter printWriter;
public MyPrinter(Product producto, Context context){
this.context = context;
this.producto = producto;
}
#Override
public void run() {
try {
socket = new Socket("192.168.0.254",9100);
printWriter = new PrintWriter(socket.getOutputStream());
printWriter.println("HELLO FROM THE THREAD");
} catch (IOException e) {
e.printStackTrace();
}
}
}
As you can see I am setting the IP and the port right there, and I've sent a ping to my printer and this is the correct IP and port. So, I don't know where the problem is, I can't see it.
The error that I obtaing from Android Studio is:
java.net.ConnectException: failed to connect to /192.168.0.254 (port 9100): connect failed: ECONNREFUSED (Connection refused)
Thank you in fordward!

UDP socket programming is not working for Android 6.0(API 23) [duplicate]

I am trying to write a simple android chat app. I have created a service class which handles all the networking communication. The DatagramSocket binding is in a separate thread. Once in while I am getting this error and the app crashes:
java.net.BindException: bind failed: EADDRINUSE (Address already in use)
at libcore.io.IoBridge.bind(IoBridge.java:89)
at java.net.PlainDatagramSocketImpl.bind(PlainDatagramSocketImpl.java:68)
at java.net.DatagramSocket.createSocket(DatagramSocket.java:133)
at java.net.DatagramSocket.<init>(DatagramSocket.java:78)
and this is the code which prodruces it. The error occur on the line with new DatagramSocket How can I avoid this error? Thank you.
private class ComThread extends Thread {
private static final int BCAST_PORT = 8779;
DatagramSocket mSocket;
InetAddress myBcastIP, myLocalIP;
public ComThread() {
try {
myBcastIP = getBroadcastAddress();
if (D)
Log.d(TAG, "my bcast ip : " + myBcastIP);
myLocalIP = getLocalAddress();
if (D)
Log.d(TAG, "my local ip : " + myLocalIP);
if (mSocket == null) {
mSocket = new DatagramSocket(BCAST_PORT);
mSocket.setReuseAddress(true);
mSocket.setBroadcast(true);
}
} catch (IOException e) {
Log.e(TAG, "Could not make socket", e);
}
}
Since Sean asked for the code, I have translated Nikola's answer to the following code, which is similar to what I am using in my app, in case it is useful:
if (mSocket == null) {
mSocket = new DatagramSocket(null);
mSocket.setReuseAddress(true);
mSocket.setBroadcast(true);
mSocket.bind(new InetSocketAddress(BCAST_PORT));
}
You need to set SO_REUSEADDR before binding. Don't specify port in the constructor - create unbound socket instead with DatagramSocket(null), then set options, then bind() explicitly.
Another reason that I faced,
In case you access a method that using your socket from an external thread, you have to make sure that the thread won't access the method more than once in the same time(or in another words won't create the socket more than one time), and despite the send and receive methods of the DatagramSocket are threadsafe, the construction of the DatagramSocket object is not, so you have to just synchronize the method that is capable of creating the DatagramSocket socket:
synchronized public void my_datagram_socket() throws Exception{
// create the socket
// operations through the socket
// whatever you want
}

Is the usage of TcpClients in unity3d for android possible?

I am trying to make an andorid app that commuicates with my server via Unity 5.4. The Devices need to be in the same network to do so.
For that i am using System.Net.Sockets and a TcpClient to connect to my server. Everything works well when i run it out of the Editor, or build it as a Windows standalone.The communication between a pc hosting the service and a diffrent pc running the standalone is possible and working as intended. As soon as i build it as an .apk and install it on my smartphone i will get a SocketException. Also my phone is stuck loading for quite some time
Is using a TcpClient, is that possible on android with unity3d ?
The Exception i get is:
System.Net.Sockets.SocketException: Connection timed out
I made sure that both devices are in the same network, e.g. the Ip for my Pc hosting the server is 192.168.178.24 and the ip for my smartphone is 192.168.178.113.
The ports required are open and the firewall lets data through.
I am runnig this code in Unity:
private TcpClient client;
private StreamWriter writer;
void Start()
{
try
{
client = new TcpClient(AddressFamily.InterNetwork);
IPAddress ipAddress = IPAddress.Parse(PlayerPrefs.GetString(MenuManager.IpPlayerPrefKey));
Debug.Log(ipAddress.ToString());
client.Connect(ipAddress, 11000);
writer = new StreamWriter(client.GetStream());
Debug.Log("connected");
}
catch (ArgumentNullException ane)
{
Debug.Log(string.Format("ArgumentNullException : {0}", ane.ToString()));
}
catch (SocketException se)
{
Debug.Log(string.Format("SocketException : {0}", se.ToString()));
}
catch (Exception e)
{
Debug.Log(string.Format("Unexpected exception : {0}", e.ToString()));
}
}
i double checked if the Ip adress recieved from the player prefs is correct, it is.
Has someone an idea what causes it to not even establish a connection ? I tried Wireshark on my pc, it didn't show any incoming packages, so my guess is the mistake is sometimes during establishing the connection.
Here is an image for my Log output from the smartphone:
LogCat Output
Edit: Server Code
public class ServiceListener
{
public TcpListener Listener;
public void StartListening()
{
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = Array.Find<IPAddress>(ipHostInfo.AddressList, ipMatch => ipMatch.AddressFamily == AddressFamily.InterNetwork);
Listener = new TcpListener(ipAddress, 11000);
Listener.Start();
}
public void StopListening()
{
Listener.Stop();
}
}
static void Main()
{
ServiceListener currentListener = new ServiceListener();
currentListener.StartListening();
TcpClient currentClient = currentListener.Listener.AcceptTcpClient();
StreamReader reader = new StreamReader(currentClient.GetStream());
Console.WriteLine("Connected");
while (true)
{
byte[] messageBytes = new byte[1024];
if (!reader.EndOfStream)
{
string message = reader.ReadLine();
string[] messageParts = message.Split('|');
int xOffset = int.Parse(messageParts[0]);
int yOffset = int.Parse(messageParts[1]);
bool leftClick = bool.Parse(messageParts[2]);
bool rightClick = bool.Parse(messageParts[3]);
Console.WriteLine(string.Format("x:{0},y:{1},left:{2},right:{3}", xOffset, yOffset, leftClick, rightClick));
}
else
{
currentClient = currentListener.Listener.AcceptTcpClient();
reader = new StreamReader(currentClient.GetStream());
}
}
}
Is using a TcpClient, is that possible on android with unity3d ?
Yes, it is. It is very possible and should work.
Your problem is very likely to come from this line of code:
IPAddress ipAddress = IPAddress.Parse(PlayerPrefs.GetString(MenuManager.IpPlayerPrefKey));
Since your hosting server IP is 192.168.178.24. Hardcode the value for testing purposes to see if PlayerPrefs.GetString(MenuManager.IpPlayerPrefKey) is returning an invalid IP Address.
Maybe something like:
IPAddress ipAddress = IPAddress.Parse("192.168.178.24");
Another thing to do in your server code is to put Application.runInBackground = true; in your Start() function. This will make sure that your server is running even when the Applciation is not on focus.
Finally, you are currently using synchronous server socket. When connecting, receiving data from the server, Unity will block/freeze until that operation completes. You should use asynchronous socket or run your server and client code in another Thread. This does not look like the current problem but you will run into it later on.

serversocket to bluetooth serversocket

For the past couple of days, I have been working on establishing a client-server socket over Bluetooth with an android server and a windows PC socket so I can send information over from the computer that can be used on an app for Oculus Gear VR (app would be on the android). I am having a big issue with the Bluetooth server socket on the android side. It doesn't help that my experience with android studio is encompassed within like 4 days. I figured out how to create a regular server socket on an android app that waits for a connection from the client
`public class MyServer {
BluetoothDevice device;
Thread m_objThread;
ServerSocket m_server;
String m_strMessage;
DataDisplay m_dataDisplay;
Object m_connected;
public MyServer()
{
}
public void setEventListener(DataDisplay dataDisplay)
{
m_dataDisplay = dataDisplay;
}
public void startListening()
{
m_objThread = new Thread(new Runnable() {
public void run() {
try {
m_server = new ServerSocket(2001);
Socket connectedSocket = m_server.accept();
Message clientmessage = Message.obtain();
ObjectInputStream ois = new ObjectInputStream(connectedSocket.getInputStream());
String strMessage = (String) ois.readObject();
clientmessage.obj = strMessage;
mHandler.sendMessage(clientmessage);
ObjectOutputStream oos = new ObjectOutputStream(connectedSocket.getOutputStream());
oos.writeObject("Hi..");
ois.close();
oos.close();
m_server.close();
} catch (Exception e) {
Message msg3 = Message.obtain();
msg3.obj = e.getMessage();
mHandler.sendMessage(msg3);
}
}
});
m_objThread.start();
}
Handler mHandler = new Handler() {
#Override
public void handleMessage(Message status)
{
m_dataDisplay.Display(status.obj.toString());
}
};
`
But I am not completely sure how to change this to a Bluetooth server socket in order to create a Bluetooth socket. Any help is appreciated, I am relatively new to coding and have only used c++ on visual studio so I am having a lot of trouble with android studio. Thanks!
You should create one thread for accepting a connection and another- for sending and receiving the data. When device is connected, you stop 'connect thread' and start 'transfer' thread. There is a gread example from google- https://github.com/googlesamples/android-BluetoothChat

The socket stop t Socket.accept() in Android for TCP Server

I try to create a Simple TCP Server on Android phone and waiting for client.
I only want to implement the connection between TCPServer and Client , it doesn't need to transmit any data.
I have the another application for client , It use to connect to this TCPServer.
The code of TCPServerthread is like the following.
private class TCPServerThread implements Runnable
{
#Override
public void run() {
// TODO Auto-generated method stub
try {
ServerSocket serverSocket = new ServerSocket(PORT);
//while loop
while (true) {
Log.i(TAG, "TCPServerThread...while loop");
try {
Socket socket = serverSocket.accept();
Log.i(TAG, "TCPServerThread...socket.getInetAddress() = " + socket.getInetAddress());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
Log.i(TAG, "First IOException");
}
}
//while loop end
} catch (Exception e) {
// TODO: handle exception
//e.printStackTrace();
Log.i(TAG, "Second IOException");
}
}
}
But it seems stop at Socket socket = serverSocket.accept(); and doesn't show the log of TCPServerThread...socket.getInetAddress() = when the client try to connect to this Server.
DO I missing something for TCPServer ?
Is it mean the client doesn't connect to the Server when the code stop at Socket socket = serverSocket.accept(); ??
----------------------------EDIT----------------------------------------
Update the process.
The Server(Android Phone) open the WiFi-Hot-Spot, it also open the TCP-Server like the above code.
After Client connect to WiFi-Hot-Spot , the Client and the Server are in the same network.
The Client will get a IP address of gateway, and the Client try to connect to this IP address of gateway by TCP.
So the connection port and Server address seems correct for Client.
Your code is correct, but it seems that no one is connecting to your TCPserver.
To avoid this blocking situation on
Socket socket = serverSocket.accept();
you have to set the timeout option for your socket when you declare it
serverSocket.setSoTimeout(mTime);
;)

Categories

Resources