1

客户端使用服务器接受的相同连接发送数据是否正确?

情况是这样的,我的 PC 上运行着蓝牙服务器,而另一方面,我有带有客户端和服务器的 android 手机。从android端客户端开始连接。我正在使用来自 android 示例的蓝牙聊天示例。

android上的服务器客户端看起来像

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

    // Get the BluetoothSocket input and output streams

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

在 PC 端,我使用Bluez库来实现服务器和客户端。
该代码包括蓝牙接收线程和一个主线程,每当服务器接受来自android手机的连接时,我只需将套接字值分配给全局变量,并且每当客户端需要发送数据时,它使用同一个套接字发送,

服务器:-

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));
....................
...................
}

客户:-

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.

4

2 回答 2

0

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';
于 2013-08-24T05:33:22.443 回答
0

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.

于 2013-08-24T06:32:37.333 回答