完善一个聊天程序(win下C语言SOCKET编程)
这两天刚学习SOCKET编程,在网上找了一篇代码,模仿敲了一遍通了。但是这个聊天程序不够完善,只能是客户端发送过来了,服务端才能说话;而也是得等服务端说话了客户端才能说话。我想做的就是每端都能随时说话。不知道用线程,然后用非阻塞的recv和send是不是就能成功?有没有大神能在我的这个基础下修改的,谢谢了!!!代码如下:
/*服务器端*/
#include<winsock2.h>
#include<stdio.h>
#include<string.h>
//#pragma comment(lib,"ws2_32.lib")
void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested=MAKEWORD(1,1);
err=WSAStartup(wVersionRequested,&wsaData);
if(err!=0)
{
return;
}
if(LOBYTE(wsaData.wVersion)!=1||HIBYTE(wsaData.wVersion)!=1)
{
WSACleanup();
return;
}
SOCKET sockSrv=socket(AF_INET,SOCK_STREAM,0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(6000);
bind(sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
listen(sockSrv,6);
char sendBuf[100];
char recvBuf[100];
char tempBuf[100];
SOCKADDR_IN addrClient;
int len=sizeof(SOCKADDR);
while(1)
{
printf("waiting for client\n");
SOCKET sockConn=accept(sockSrv,(SOCKADDR*)&addrClient,&len);
recv(sockConn,tempBuf,100,0);
if(tempBuf[0]!='q')
{
sprintf(recvBuf,"%s say: %s",inet_ntoa(addrClient.sin_addr),tempBuf);
printf("%s\n",recvBuf);
printf("please input your data,server:\n");
gets(sendBuf);
send(sockConn,sendBuf,strlen(sendBuf)+1,0);
}
else
{
printf("%s request to quit the chat platform",inet_ntoa(addrClient.sin_addr));
send(sockConn,"q",strlen("q")+1,0);
closesocket(sockConn);
break;
}
}
closesocket(sockSrv);
WSACleanup();
}
/*客户端*/
#include<winsock2.h>
#include<stdio.h>
#include<string.h>
//#pragma comment(lib,"ws2_32.lib")
void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested=MAKEWORD(1,1);
err=WSAStartup(wVersionRequested,&wsaData);
if(err!=0)
{
return;
}
if(LOBYTE(wsaData.wVersion)!=1||HIBYTE(wsaData.wVersion)!=1)
{
return;
}
while(1)
{
SOCKET sockClient=socket(AF_INET,SOCK_STREAM,0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(6000);
char sendBuf[100];
char tempBuf[100];
char recvBuf[100];
int len=sizeof(SOCKADDR);
connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
printf("please input your data,client:\n");
gets(sendBuf);
printf("waiting for server\n");
send(sockClient,sendBuf,sizeof(sendBuf)+1,0);
recv(sockClient,tempBuf,100,0);
if(tempBuf[0]!='q')
{
sprintf(recvBuf,"server say: %s",tempBuf);
printf("%s\n",recvBuf);
}
else
{
printf("the server has been closed!\n");
send(sockClient,"q",strlen("q")+1,0);
break;
}
}
//closesocket(sockClient);
WSACleanup();
}
[解决办法]
异步套接字
[解决办法]
不知道有多少前人掉在TCP Socket
send(人多)send(病少)send(财富)
recv(人多病)recv(少财富)
陷阱里面啊!
http://topic.csdn.net/u/20120210/09/51109ed0-07b9-41f2-b487-a51597f2ca01.html
[解决办法]
这里有些WinSock的源码,有服务器端也有客户端,你可以参考一下:
http://download.csdn.net/detail/geoff08zhang/4571358