关于VC++ socket如何实现聊天全双工,下面这个程序实现了单工,那位大虾给改成全双工的,(实现两方可以完全任意的发送消息,而不用你一句,对方一句那样发)多谢,急急急!!!
1、UDPchatcli端
#include <winsock2.h>
#include <stdio.h>
void main()
{
WSADATA wsaData;
WSAStartup(WINSOCK_VERSION,&wsaData);
SOCKET client = socket(AF_INET,SOCK_DGRAM,0);
struct sockaddr_in svraddr;
memset(&svraddr,0,sizeof(svraddr));
svraddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
svraddr.sin_family = AF_INET;
svraddr.sin_port = htons(9999);
char sendbuf[100];
char recvbuf[100];
int len = sizeof(sockaddr);
while(1)
{
gets(sendbuf);
sendto(client,sendbuf,sizeof(sendbuf)+1,0,(struct sockaddr *)&svraddr,len);
if ('q'==sendbuf[0])
{
printf("Chat end!");
break;
}
recvfrom(client,recvbuf,sizeof(recvbuf),0,(struct sockaddr *)&svraddr,&len);
printf("%s\n",recvbuf);
if ('q'==recvbuf[0])
{
printf("Chat end!");
break;
}
}
closesocket(client);
WSACleanup();
}
2、UDPchatserver端
#include <winsock2.h>
#include <stdio.h>
void main()
{
WSADATA wsaData;
WSAStartup(WINSOCK_VERSION,&wsaData);
SOCKET svr=socket(AF_INET,SOCK_DGRAM,0);
struct sockaddr_in svraddr,clientaddr;
memset(&svraddr,0,sizeof(svraddr));
svraddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
svraddr.sin_family = AF_INET;
svraddr.sin_port = htons(9999);
bind(svr,(struct sockaddr *)&svraddr,sizeof(svraddr));
char recvbuf[100];
char sendbuf[100];
int len = sizeof(sockaddr);
printf("This is server.");
while(1)
{
recvfrom(svr,recvbuf,sizeof(recvbuf),0,(struct sockaddr *)&clientaddr,&len);
printf("%s say %s\n",inet_ntoa(clientaddr.sin_addr),recvbuf);
if ('q'==recvbuf[0])
{
printf("Chat end!");
break;
}
printf("Please input data:\n");
gets(sendbuf);
sendto(svr,sendbuf,sizeof(sendbuf)+1,0,(struct sockaddr *)&clientaddr,len);
if ('q'==sendbuf[0])
{
printf("Chat end!");
break;
}
}
closesocket(svr);
WSACleanup();
}