客户端发送的socket数据,需要客户端断开连接之后服务器端才能受到,为何
android手机为服务器端,PC端软件为客户端
PC客户端通过socket发送数据给服务器端,服务器端一直接收不到数据,只有当PC客户端断开socket连接之后,
手机服务器端才接收到数据,请问是怎么回事?怎么处理,谢谢
代码如下:
android 手机端linux(server)
int make_server_socket()
{
int sockfd = socket(PF_INET, SOCK_STREAM, 0);
struct sockaddr_in my_addr;
memset(&my_addr, 0, sizeof(my_addr));
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(LISTENPORT);
my_addr.sin_addr.s_addr = INADDR_ANY;
if(sockfd>0)
{
int on = 1;
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
if(bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr))==0)
{
if(listen(sockfd, 0)==0)
{
// No error
}
else
{
close(sockfd);
sockfd = -3;
}
}
else
{
close(sockfd);
sockfd = -2;
}
}
return sockfd;
}
int accept_socket(int sockfd)
{
// Block until connections
struct sockaddr_in peer_addr;
unsigned int sin_size = sizeof(peer_addr);
int new_fd = accept(sockfd, (struct sockaddr *)&peer_addr, &sin_size);
return new_fd;
}
int recv_socket(int sockfd, void* buffer, int size)
{
int received = 0;
while (buffer && received < size)
{
int result = recv(sockfd, buffer + received, size - received, MSG_NOSIGNAL);
if (result > 0)
{
received += result;
}
else
{
received = result;
break;
}
}
return received;
}
.............
while (1)
{
listenfd = make_server_socket();
memset(receive_buffer,0,sizeof(receive_buffer));
if (listenfd > 0)
{
while (1)
{
tcpipfd = accept_socket(listenfd);
if (tcpipfd > 0)
{
len=recv_socket(tcpipfd, recmsg, BUF_LEN_1024);
}
else
{
break;
}
sleep(1);
}
close_socket(listenfd);
}
sleep(2);
}
............
java客户端:
byte[] bs = new byte[] { (byte) 127, (byte) 0, 0, 1 };
InetAddress addr = InetAddress.getByAddress(bs);
pcsocket =new Socket(addr,port);
sender=new BufferedOutputStream(pcsocket.getOutputStream(),20);
receiver=new BufferedInputStream(pcsocket.getInputStream(),20);
sender.write(data.getBytes(),0,data.length());
sender.write('\n');
sender.flush();
------解决方案--------------------
你一直循环read,又写不足size个字节,while怎么退出?
只有
else
{
received = result;
break;
}退出才打印结果。