在我的服务器中,我向套接字发送一个无限循环的(“数字:%d\n”,i)。而且,在每个循环中,我都会将数字增加一。然后我使用以下代码在 android 设备(即 TCP 客户端)中接收它:while(connected){
//receive data through socket
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.d(TAG, "1");
while(connected){
//receive data through socket
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.d(TAG, "1");
while ( (line = in.readLine()) != null){
Log.d(TAG, line);
str.append(line);
Log.d(TAG, "2");
runOnUiThread(new Runnable() {
@Override
public void run() {
input.setText( str );
}});
}
}
这是 logcat 的结果:
r:25363332´┐¢编号:3405er:3839er:4201er:4925´┐¢编号:557776228¢编号:6301´┐¢编号:7265€¢编号:7265´┐ ´┐¢号码: 1173112020´┐¢号码: 12093´┐¢号码: 12455号码: 12672er: 13491´┐¢号码: 13903er: 14337er: 14699´┐¢号码: 15351´┐¢¢号码: 157361er: 16147号码:1643716726´┐¢号码:16799号码:17016号码:173 787´┐¢号码:17885号码:187047´┐¢号码:19695er:201291´┐¢号码:20419´┐¢号码:207813´┐2号码:207813´┐2号码:511 :2157721794´┐¢编号:21867er:2230122518n umber:22808er:23627244446´┐¢编号:25125er:2555592637872794848€
所以这不能识别 \n,并且在套接字读取之间它正在丢失数据。是因为 UI 线程的不断实现吗?
我应该怎么做呢?
更新
这是 C 语言中的服务器代码:
int main(int argc, char **argv)
{
socklen_t client_len;
struct sockaddr_in cli_addr;
struct sockaddr_in serv_addr;
int client_count=0;
int nbytes, i, sockfd, new_sockfd;
char buf[20];
/* Init socket */
sockfd=socket(AF_INET, SOCK_STREAM, 0);
if (sockfd<0) error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons( atoi(argv[1]) );
/*associate socket to the port*/
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) error("ERROR on binding");
/* connection to the client */
listen(sockfd, 1); /*server is ready to receive connections*/
client_len = sizeof(cli_addr);
new_sockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &client_len); /*server accepts request */
client_count =1; /*write to socket when client is available*/
i = 1;
while(1){
sprintf(buf, "number: %d\n", i);
if (client_count >0){
nbytes = write( new_sockfd, buf, sizeof(buf)); /* write to socket */
if(nbytes<0){
printf("ERROR on sendto");
}
}
i = i+1;
}
return (0);
}