基于DOS平台下SOCKET编程
首先创建服务器端程序
void main()
{
//首先加载套接字库,我这里用的是1.1版本,有兴趣的可以联2.0库,可以获得更多功能啊
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 1, 1 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
return false;
}
if ( LOBYTE( wsaData.wVersion ) != 2 ||
HIBYTE( wsaData.wVersion ) != 2 ) {
WSACleanup( );
return false;
}
//创建套接字,在这之前,还要加两个头文件和一个库文件,分别是
#include <Winsock2.h>
#include <stdio.h>
库文件要在设置.工程里面的连接选项中加入Use Ws2_32.libSOCKET s=socket(AF_INET,SOCK_DGRAM,0);
SOCKADDR_IN sockAddr;
sockAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
sockAddr.sin_family = AF_INET;
sockAddr.sin_port = htons(5000);//这里的端口可以随便设置,但必须和客户端的一致
//绑定套接字
bind(s,(sockaddr*)&sockAddr,sizeof(sockaddr));
char recvBuff[100];
char sendBuff[100];
char tempBuff[100];
SOCKADDR_IN sockFrom;
int len = sizeof(sockaddr);
while(true)
{
::recvfrom(s,recvBuff,100,0,(sockaddr*)&sockFrom,&len);
if('q' == recvBuff[0])
{
printf("Chat end!/n");
sendto(s,"q",strlen("q")+1,0,(sockaddr*)&sockFrom,len);
break;
}
sprintf(tempBuff,"%s say: %s",inet_ntoa(sockFrom.sin_addr),recvBuff);
printf("%s/n",tempBuff);
gets(sendBuff);
sendto(s,sendBuff,strlen(sendBuff)+1,0,(sockaddr*)&sockFrom,len);
}
closesocket(s);
WSACleanup( );
}
再来编写客户端代码
再先前的工作空间中建立一个工程UdpClient,至于加入头文件客库文件和服务器端一模一样
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 s = socket(AF_INET,SOCK_DGRAM,0);
SOCKADDR_IN sockAddr;
sockAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
sockAddr.sin_family = AF_INET;
sockAddr.sin_port = htons(5000);
char sendBuff[100];
char recvBuff[100];
char tempBuff[100];
printf("聊天通道已经完成,开始吧!/n");
SOCKADDR_IN sockFrom;
int len = sizeof(sockaddr);
while(true)
{
gets(sendBuff);
sendto(s,sendBuff,strlen(sendBuff)+1,0,(sockaddr*)&sockAddr,sizeof(sockaddr));
recvfrom(s,recvBuff,100,0,(sockaddr*)&sockFrom,&len);
if('q' == recvBuff[0])
{
printf("Chat End!/n");
sendto(s,"q",strlen("q")+1,0,(sockaddr*)&sockFrom,sizeof(sockaddr));
break;
}
sprintf(tempBuff,"%s say: %s",inet_ntoa(sockFrom.sin_addr),recvBuff);
printf("%s/n",tempBuff);
}
closesocket(s);
WSACleanup( );
}
这样,一个简单的聊天程序就完成了,但是它还有很多缺陷,比如说基于DOS的,客户端必须先发送数据,然后才是服务器端,交互性很差,由于它是基于UDP协议的,稳定性不是很理想,但作为初期的网络编程练习,我觉得还是恨道的,希望对你有帮助!