I am writing a pc & phone communication app. The pc code is written in C#. When I connect my phone (which is paired with pc) to my pc, the phone connects however the logs say, the socket is not connected i-e; socket.isConnected() returns false on my phone. I have tried to run this app on multiple phones and the problem persists.
I think the issue is with my C# code as I don't know C# well.
Following is the c# code:
BluetoothListener blueListener = new BluetoothListener(mUUID);
blueListener.Start();
BluetoothClient conn = blueListener.AcceptBluetoothClient();
if(conn.Connected)
updateUI("Mobile connected");
Stream mStream = conn.GetStream();
while (true)
{
try
{
byte[] received = new byte[1024];
mStream.Read(received, 0, received.Length);
//.....
}
catch() {}
}
I am using 32feet library in C#.
Following is my Android code:
BluetoothSocket socket = selectedDevice.createRfcommSocketToServiceRecord(deviceUUID);
try
{
socket = openSocketForSendingData();
try
{
BluetoothAdapter bAdapter = BluetoothAdapter.getDefaultAdapter();
bAdapter.cancelDiscovery();
socket.connect();
Log.e("NP socket", "No Exception");
}
catch(Exception e)
{
Log.e("NP socket Exception", e.toString());
}
if(socket == null)
Log.e("Socket NULL", "socket is null");
if(!socket.isConnected())
{
Log.e("NP socket", "socket not cconnected");
try
{
socket.close();
}
catch(Exception e)
{
Log.e("Socket CLOSE",e.toString());
}
}
else
Log.e("NP socket", "socket cconnected");
if(socket.getOutputStream() == null)
Log.e("Soccket Outupt", "output stream null");
dos = new DataOutputStream(socket.getOutputStream());
dos.writeChars("Hello World I am android");
}
catch(Exception e)
{
Log.e("NP writing socket", e.toString());
}
The UUID in both codes is same.
Can you guide me what mistake am I making?
PS: Before asking this question, I have already spent all day searching the solution on internet, but it was no good.
Regards
Related
Error Java.Net.SocketException: Binding socket to network 626 failed: ENONET (Machine is not on the network)
Xamarin app: this method is written for android.
I am getting this error, it is not reported every time, it is difficult for me to capture it in test environments.
Why is this error, what is the explanation?
what can be done to have better control in this method?
There is a similar question asked some time ago, but it does not the same operation that I do here, and it is not solved.
public static void BindSocketToWifi(Socket socket)
{
try
{
ConnectivityManager connectivityManager = (ConnectivityManager)Android.App.Application.Context.GetSystemService(Context.ConnectivityService);
NetworkInfo wifiInfo = null;
var networks = connectivityManager.GetAllNetworks();
foreach (var net in networks)
{
wifiInfo = connectivityManager.GetNetworkInfo(net);
if (wifiInfo.Type == ConnectivityType.Wifi)
{
try
{
net.BindSocket((Socket)socket);
}
catch (Exception ex)
{
Crashes.TrackError(ex);
throw ex;
}
break;
}
}
}
catch (Exception e)
{
Crashes.TrackError(e);
throw e;
}
}
I'm using a very standard UDP client code. It works fine in Unity Editor. But when build to android phone, I got no response. The sender is a well tested windows program (I also tried other udp senders from online) and I'm only building a receiver client. The sender is in UDP broadcast mode and is sending to 255.255.255.255:60888. It works fine In Unity but when build on the phone, it prints nothing. However toggling the sender to direct ip of the phone, it works fine and prints out the data. I have tried putting the receive EndPoint with IPAddress.Broadcast/Any/255.255.255.255/192.168.1.255.
They all work in editor but none works in android. Tried other ports too and same. I have read something about multicast lock from android and tried, not working.
Some suggested HTC is not receiving broadcast (hardware specific). However the phone (not HTC) has a built-in video player that can be triggered buy a udp broadcast. My sender can send through and pull up the player. I think that is a native app and using java Datagram Socket. I wonder if this is a Unity bug or firmware bug.
Unity version tried: 5.6.3, 2017.2.1, 2017.4.2.
Code is below:
public class UDPClient : MonoBehaviour {
Thread receiveThread;
int remotePort = 60888;
int clientPort = 60666;
UdpClient _udpClient;
// Use this for initialization
void Start ()
{
if (Application.isEditor)
{
Application.runInBackground = true;
}
_udpClient = new UdpClient(clientPort);
_udpClient.Client.ReceiveBufferSize = 1024;
receiveThread = new Thread(new ThreadStart(ReceiveTask));
receiveThread.Start();
}
void ReceiveTask()
{
IPEndPoint remoteEP = new IPEndPoint(IPAddress.Broadcast, 0);
while (true)
{
try
{
byte[] data = _udpClient.Receive(ref remoteEP);
if (data != null && data.Length > 0)
{
Debug.Log("received: " + remoteEP.ToString() + " length: " + data.Length + " data: " + data[1].ToString());
}
else {
Thread.Sleep(10);
}
}
catch (System.Exception ex)
{
throw (ex);
}
}
}
void CleanUp()
{
Debug.Log("cleanning Thread");
if (receiveThread != null)
{
receiveThread.Abort();
}
receiveThread = null;
_udpClient.Close();
_udpClient = null;
}
void OnApplicationQuit()
{
CleanUp();
}
}
I am trying to listen at incoming Bluetooth connection thanks to this code based on this documentation:
public void WaitForConnection()
{
BluetoothServerSocket serverSocket = null;
BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;
if (adapter == null)
throw new Exception("No Bluetooth adapter found");
if (!adapter.IsEnabled)
throw new Exception("Bluetooth adapter is not enabled");
// Create a new listening server socket
try
{
serverSocket = adapter.ListenUsingRfcommWithServiceRecord("MindCam", UUID.FromString(Ev3UUID));
}
catch (Java.IO.IOException e)
{
Console.WriteLine("Error listening connection: " + e.Message);
}
Task t = Task.Factory.StartNew(() =>
{
while (true)
{
try
{
_socket = serverSocket.Accept();
}
catch (IOException e)
{
Console.WriteLine("Socket's accept() method failed");
break;
}
if (_socket != null)
{
// A connection was accepted.
serverSocket.Close();
Console.WriteLine("Connection accepted");
break;
}
}
});
}
I call this method at the beginning of an activity. I debug that, and it seems that the code is executed until "serverSocket.Accept()", and even if it is not awaited, the code is no more executed. Afterwards, even when I attempt to make a connection from a Bluetooth device (a Mindstorms brick) to the Android device, it is not detected and this thread doesn't continue...
Why doesn't this work ?
Thanks in advance.
I am starting on Android and in my first application I need to establish a communication between and android table a PC. The communication is direct by staqtic IPs as I need that when I have several PCs and tablets each table only communicates with its PC.
The communication from the tablet to the Pc is already working but from the PC to the table I cannot get data transfered
Android side
public class Server implements Runnable
{
#Override
public void run()
{
while (always==true)
{
while(start2==false)
{
}
try
{
InetAddress serverAddr = InetAddress.getByName("192.168.173.133");
updatetrack("\nServer: Start connecting\n");
//*DatagramSocket socket = new DatagramSocket(SERVERPORT2, serverAddr);/
DatagramSocket socket = new DatagramSocket(SERVERPORT2);
byte[] buf = new byte[17];
DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, SERVERPORT2);
//*DatagramPacket packet = new DatagramPacket(buf, buf.length);/
updatetrack("Server: Receiving\n");
socket.receive(packet);
updatetrack("Server: Message received: '" + new String(packet.getData()) + "'\n");
updatetrack("Server: Succeed!\n");
start2=false;
}
catch (Exception e)
{
updatetrack("Server: Error!\n");
start2=false;
}
}
}
}
192.168.173.133 is the table IP and SERVERPORT2 is 4445
When I start the application it remains waiting for data after displaying "Server: Receiving" but
C# code
public static void Main()
{
IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse("192.168.173.133"), 4445);
string hostname = Dns.GetHostName();
byte[] data = Encoding.ASCII.GetBytes(hostname);
sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
sock.SendTo(data, iep2);
sock.Close();
}
I suppose that it is any silly think I am forgotten but after reading many forums and books I am stopped on this point
Any advise will be welcome
You use UDP connection and socket.receive(packet) doesn't wait for packet. If there isn't packet in the buffer this operation throw exception.
Try to change your code to:
#Override
public void run()
{
while (always==true)
{
while(start2==false)
{
}
try
{
InetAddress serverAddr = InetAddress.getByName("192.168.173.133");
updatetrack("\nServer: Start connecting\n");
//*DatagramSocket socket = new DatagramSocket(SERVERPORT2, serverAddr);/
DatagramSocket socket = new DatagramSocket(SERVERPORT2);
while (always==true)
{
try{
byte[] buf = new byte[17];
DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, SERVERPORT2);
//*DatagramPacket packet = new DatagramPacket(buf, buf.length);/
updatetrack("Server: Receiving\n");
socket.receive(packet);
updatetrack("Server: Message received: '" + new String(packet.getData()) + "'\n");
updatetrack("Server: Succeed!\n");
start2=false;
}
catch(Exception ex) {ex.printStackTrace();}
}
}
catch (Exception e)
{
updatetrack("Server: Error!\n");
start2=false;
}
}
}
This is a follow on from this question
After some more Googling last night I managed to find a nice TCP tutorial I could follow that would allow me to look for connections on an Ip address and port number and display the data that is being sent.
However, I have an issue where my client connects once, I send a message and display it in the debug log but when I stop the application and run it again, Unity freezes. I'm at a loss as to why this happening. Could someone please take a look over this code to see where it might be happening and what I can do to fix it?
I also seem to boot out the connection as soon as I receive a message as well, why is that? The server can re-connect, but I want it to keep the connection once it has it.
public class TCP : MonoBehaviour
{
string ip_address = "127.0.0.1";
int port = 22;
Thread listen_thread;
TcpListener tcp_listener;
Thread clientThread;
TcpClient tcp_client;
bool isTrue = true;
// Use this for initialization
void Start ()
{
IPAddress ip_addy = IPAddress.Parse(ip_address);
tcp_listener = new TcpListener(ip_addy, port);
listen_thread = new Thread(new ThreadStart(ListenForClients));
listen_thread.Start();
Debug.Log("start thread");
}
private void ListenForClients()
{
this.tcp_listener.Start();
while(isTrue == true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcp_listener.AcceptTcpClient();
//create a thread to handle communication
//with connected client
clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
Debug.Log("Got client " + client);
}
}
private void HandleClientComm(object client)
{
tcp_client = (TcpClient)client;
NetworkStream client_stream = tcp_client.GetStream();
byte[] message = new byte[4096];
int bytes_read;
while(isTrue == true)
{
bytes_read = 0;
try
{
//blocks until a client sends a message
bytes_read = client_stream.Read(message, 0, 4096);
//Debug.Log(message);
}
catch (Exception e)
{
//a socket error has occured
Debug.Log(e.Message);
break;
}
if(bytes_read == 0)
{
//client has disconnected
Debug.Log("Disconnected");
tcp_client.Close();
break;
}
ASCIIEncoding encoder = new ASCIIEncoding();
Debug.Log(encoder.GetString(message,0,bytes_read));
}
if(isTrue == false)
{
tcp_client.Close();
Debug.Log("closing tcp client");
}
}
void OnApplicationQuit()
{
try
{
tcp_client.Close();
isTrue = false;
}
catch(Exception e)
{
Debug.Log(e.Message);
}
}
}
Here is a screen shot of my debug log as well to show whats happening:
update
updated code that has fixed the kicking of clients. The freeze issue is still persistent when I stop the unity application and re-start it.
further update
So after a little further experimenting I have worked out that my project isn't actually freezing. When I start the server (Unity) app the first time everything works fine. But when I close it and try to re run the server, it freezes, until I connect to it with a client. At which point the server works as normal.
So I think I'm not closing the open socket when I close down the server. How can I do that?
You must close the TCP socket that is listening. If you start the application for the first time, the TCP socket will be open. When you stop the application, the TCP socket is still opened and runs in the background.
void OnApplicationQuit()
{
try
{
tcp_client.Close();
isTrue = false;
}
catch(Exception e)
{
Debug.Log(e.Message);
}
// You must close the tcp listener
try
{
tcp_listener.Stop();
isTrue = false;
}
catch(Exception e)
{
Debug.Log(e.Message);
}
}