Question

Is it right method client send data using the same connection accepted by server?.

The situation is like this, I have blue tooth server running on my PC and on the other side I have android phone with client and server. From android side the client start connection. I am using blue-tooth chat example from android samples.

And the server-client on android look like

     BluetoothSocket socket;
     InputStream tmpIn = null;
     OutputStream tmpOut = null;

    // Get the BluetoothSocket input and output streams

        tmpIn = socket.getInputStream();
        tmpOut = socket.getOutputStream(); 

And in the PC side I am using Bluez libraries to implement server and client.
The code includes blue tooth receive thread and a main thread, whenever the server accept a connection from android phone I just assign the socket value to a global variable and whenever the client need to send data it send using the same socket ,

Server:-

int GLOBAL_CLIENT;
void* recive_bluetooth_trd(void*)
{
...............................
..............................
 client = accept(s, (struct sockaddr *)&rem_addr, &opt);
 GLOBAL_CLIENT=client;

 while(1){
    bytes_read = read(client, buf, sizeof(buf));
....................
...................
}

Client:-

void clinet(char *msg, int length){
........................

 int bytes_write=write(GLOBAL_CLIENT,message, length);

..........................
}

My question is, Is it a right method ? The problem is that some times the client send data successfully from PC but not receiving on android side.

Was it helpful?

Solution

The biggest problem I see is that you won't ever leave your while(1) loop, even when the client disconnects. Read will return immediately forever with 0 bytes read (check for a return code of <= 0), trying to signal that the socket is disconnected. Your code will go into a tight infinite loop and use up all the CPU resources it can get its single-threaded hands on.

You need to make sure you ALWAYS check your socket and IO return codes and handle the errors correctly. The error handling for sockets is usually about 3x the actual socket code.

Unless of course the .......... stuff is the important bits. Always tough to tell when people hide code relevant to the question they are asking.

OTHER TIPS

Seems correct to me, but after read you have to NUL ('\0') terminate your buffer if you are treating with strings:

buf[bytes_read] = '\0';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top