- 论坛徽章:
- 0
|
这是我写的一段代码,实现通过Socket,即可以收消息,也可以随时发消息.
但是问题是,现在代码在运行到Read那里,也就是等待用于输入的时候,是阻塞的,如果不输入消息发出去,外面的消息就收不到.有高手可以指点一下吗,实现随时同时收发消息.
int main(int argc, char** argv)
{
struct sockaddr_in sa;
struct sockaddr_in to;
int srcsock;
int bindld, selectld,recvld;
char buff[1024];
char sendbuff[1024];
int port = 1234;
int sendport = 4321;
int len;
struct timeval timeout = {1,0};
fd_set readfds,writefds;
srcsock = socket(AF_INET, SOCK_DGRAM, 0);
if(srcsock < 0)
{
printf("socket set up error!\n");
return -1;
}
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = inet_addr("172.16.16.60");
sa.sin_port = htons(port);
to.sin_family = AF_INET;
to.sin_addr.s_addr = inet_addr("172.16.30.3");
to.sin_port = htons(sendport);
bindld = bind(srcsock, (struct sockaddr *)&sa, sizeof(struct sockaddr_in));
if(bindld < 0)
{
printf("bind error!\n");
return -1;
}
while(1)
{
FD_ZERO(&writefds);
FD_SET(srcsock, &writefds);
memcpy(&readfds, &writefds, sizeof(fd_set));
selectld = select(srcsock + 1, &readfds, &writefds, NULL, 0);
if(selectld < 0)
{
printf("select error!\n");
return -1;
}
if(FD_ISSET(srcsock, &readfds))
{
struct sockaddr_in from;
socklen_t fromlen = sizeof(from);
memset(buff, 0, 1024);
recvld = recvfrom(srcsock, buff, sizeof(buff) - 1, 0, (struct sockaddr *) &from, &fromlen);
if(recvld < 0)
printf("revice message error!\n");
else
{
buff[recvld] = 0;
printf("recive message from %s\nmessage is: %s\n",inet_ntoa(from.sin_addr), buff);
}
}
if(FD_ISSET(srcsock, &writefds))
{
memset(sendbuff,0,1024);
printf("enter msg:\n");
len = read(STDIN_FILENO, sendbuff, sizeof(sendbuff));
sendto(srcsock, sendbuff, len, 0, (struct sockaddr *) &to, sizeof(struct sockaddr_in));
}
}
} |
|