tcp简单实现C/S模式程序,测试成功
tcp简单实现C/S模式程序,测试成功
2010年03月25日
server:
#include
#include
#pragma comment(lib,"ws2_32")
main()
{
WSADATA wsaData;
SOCKET ListeningSocket;
SOCKET NewConnection;
SOCKADDR_IN ServerAddr;
SOCKADDR_IN ClientAddr;
int port=5150;
int ClientAddrLen =sizeof(ServerAddr);
char buf[4096];
//startup...
if((WSAStartup(MAKEWORD(2,2),&wsaData))!=0)
{
printf("初始化失败");
exit(-1);
}
// listening....
if((ListeningSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==INVALID_SOCKET)
{
printf("创建套接字失败");
exit(-1);
}
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_port = htons(port);
ServerAddr.sin_addr.s_addr =htons(INADDR_ANY);
// bind..
if(bind(ListeningSocket,(SOCKADDR *)&ServerAddr,sizeof(ServerAddr))==SOCKET_ERROR)
{
printf("bind error");
exit(-1);
}
if(listen(ListeningSocket,5)==SOCKET_ERROR)
{
printf("listening error..");
exit(-1);
}
printf("listening...");
//accept..
if((NewConnection = accept(ListeningSocket,(SOCKADDR *)&ClientAddr,&ClientAddrLen))==INVALID_SOCKET)
{
printf("accept error..");
exit(-1);
}
while(1)
{
int bytes;
if((bytes=recv(NewConnection,buf,sizeof(buf),0))==SOCKET_ERROR)
{
printf("recv error...");
exit(-1);
}
buf[bytes]='\0';
printf("data from %s:%s\n",inet_ntoa(ClientAddr.sin_addr),buf);
if(send(NewConnection,buf,bytes,0)==SOCKET_ERROR)
{
printf("send error..");
exit(-1);
}
}
closesocket(NewConnection);
closesocket(ListeningSocket);
WSACleanup();
}
//******************************************************************************************************************************//
client:
[/b]
#include
#include
#pragma comment(lib,"ws2_32")
main()
{
WSADATA wsaData;
SOCKET s;
SOCKADDR_IN ServerAddr;
int port =5150;
char buf[4096];
int bytes;
if(WSAStartup(MAKEWORD(2,2),&wsaData)!=0)
{
printf("stratup error..");
exit(-1);
}
if((s = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==INVALID_SOCKET)
{
printf("socket error..");
exit(-1);
}
ServerAddr.sin_family =AF_INET;
ServerAddr.sin_port = htons(port);
ServerAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
if(connect(s,(SOCKADDR *) &ServerAddr,sizeof(ServerAddr))==SOCKET_ERROR)
{
printf("connect error...");
exit(-1);
}
//****************************************************************************//
while(1)
{
printf(">>");
gets(buf);
if(send(s,buf,strlen(buf),0)==SOCKET_ERROR)
{
printf("send error..");
exit(-1);
}
if(bytes=recv(s,buf,sizeof(buf),0)==SOCKET_ERROR)
{
printf("recv error");
exit(-1);
}
}
buf[bytes]='\0';
printf("data from %s:%s",inet_ntoa(ServerAddr.sin_addr),buf);
//******************************************************************************//
closesocket(s);
WSACleanup();
}
[b]虽说非常简单,但是经过不断的丰满功能 也是个开始的框架 只是任何网络编程书中最最基础和简单的例子,啧啧,花了点点时间测试~ 咳咳,会做出来有用的东西的…