// Server.cpp : Defines the entry point for the console application.
// Author:Mandy 20161027
#include "winsock2.h"
#pragma comment(lib, "ws2_32.lib")
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
const int BUF_SIZE = 64;
WSADATA wsd; //WSADATA变量
SOCKET sServer; //服务器套接字
SOCKET sClient; //客户端套接字
SOCKADDR_IN addrServ;; //服务器地址
struct Buf //接收数据缓冲区
{
int apple;
int orange;
int banana;
char blueberry[5];
int kiwifruit;
};
Buf Buf1;
struct sendBuf //返回给客户端数据
{
int cmd;
int sendID;
int recvID;
char name[5];
int number;
};
sendBuf sendBuf1;
int retVal; //返回值
//初始化套结字动态库
if (WSAStartup(MAKEWORD(2,2), &wsd) != 0)
{
cout << "WSAStartup failed!" << endl;
return -1;
}
//创建套接字
sServer = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(INVALID_SOCKET == sServer)
{
cout << "socket failed!" << endl;
WSACleanup();//释放套接字资源;
return -1;
}
//服务器套接字地址
addrServ.sin_family = AF_INET;
addrServ.sin_port = htons(4999);
addrServ.sin_addr.s_addr = INADDR_ANY;
//绑定套接字
retVal = bind(sServer, (LPSOCKADDR)&addrServ, sizeof(SOCKADDR_IN));
if(SOCKET_ERROR == retVal)
{
cout << "bind failed!" << endl;
closesocket(sServer); //关闭套接字
WSACleanup(); //释放套接字资源;
return -1;
}
//开始监听
retVal = listen(sServer, 1);
if(SOCKET_ERROR == retVal)
{
cout << "listen failed!" << endl;
closesocket(sServer); //关闭套接字
WSACleanup(); //释放套接字资源;
return -1;
}
//接受客户端请求
sockaddr_in addrClient;
int addrClientlen = sizeof(addrClient);
sClient = accept(sServer,(sockaddr FAR*)&addrClient, &addrClientlen);
if(INVALID_SOCKET == sClient)
{
cout << "accept failed!" << endl;
closesocket(sServer); //关闭套接字
WSACleanup(); //释放套接字资源;
return -1;
}
while(true){
//接收客户端数据
char buf[BUF_SIZE];
memset(buf,0,BUF_SIZE);
retVal = recv(sClient,buf,sizeof(buf),0);
memset(&Buf1,0,sizeof(Buf));
memcpy(&Buf1,buf,sizeof(Buf));
if (SOCKET_ERROR == retVal)
{
cout << "recv failed!" << endl;
closesocket(sServer); //关闭套接字
closesocket(sClient); //关闭套接字
WSACleanup(); //释放套接字资源;
return -1;
}
//接收客户端数据
cout << "从客户端接收的数据:" <<Buf1.apple << Buf1.orange<<Buf1.banana<<Buf1.blueberry << Buf1.kiwifruit <<endl;
cout << "向客户端发送数据:" ;
cin >> sendBuf1.cmd >> sendBuf1.sendID >> sendBuf1.recvID >>sendBuf1.name >>sendBuf1.number ;
int len_send = send(sClient,(char *)&sendBuf1,sizeof(sendBuf),0);
}
//退出
closesocket(sServer); //关闭套接字
closesocket(sClient); //关闭套接字
WSACleanup(); //释放套接字资源;
return 0;
}