TCP小聊天具体代码实现(VC++)

作者在 2011-05-06 17:40:56 发布以下内容

//TCPserver:
#include<Winsock2.h>
#include<stdio.h>

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,5);
SOCKADDR_IN addrClient;
int len=sizeof(SOCKADDR);
printf("等待连接……\n");

while(1)
{
SOCKET sockConn=accept(sockSrv,(SOCKADDR*)&addrClient,&len);
bool flag= 1;
while(flag)
{
char recvBuf[100];
recv(sockConn,recvBuf,100,0);
if(recvBuf[0]=='q')
{
flag=0;
closesocket(sockConn);
continue;
}
printf("client : %s\n",recvBuf);
char sendBuf[100];
printf("server : ");
gets(sendBuf);
send(sockConn,sendBuf,strlen(sendBuf)+1,0);
}
}
}


//TCPclient
#include<Winsock2.h>
#include<stdio.h>
void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD(1,1);

err = WSAStartup(wVersionRequested,&wsaData);
if(err!=0)
return;

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);
connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
printf("对话开始:\n");
while(1)
{
char recvBuf[100];
printf("client : ");
gets(recvBuf);
send(sockClient,recvBuf,strlen(recvBuf)+1,0);
if('q'==recvBuf[0])
{
closesocket(sockClient);
WSACleanup();
break;
}
recv(sockClient,recvBuf,100,0);
printf("server : %s\n",recvBuf);
}
}

TCPserver和TCPclient | 阅读 1160 次
文章评论,共0条
游客请输入验证码
浏览2218次