// SocketServer.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<winsock2.h>
#include<iostream>
#include<fstream>
using namespace std;
#pragma comment(lib, "ws2_32.lib")
#define PORT 5000
#define MAXLISTEN 5
void _tmain(int argc, _TCHAR* argv[])
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD(2, 2);
err = WSAStartup(wVersionRequested, &wsaData);
if(err != 0)
{
return;
}
if(LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2)
{
WSACleanup();
return;
}
SOCKET sock;
sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == INVALID_SOCKET)
{
printf("socket fail !");
Sleep(3000);
return ;
}
struct sockaddr_in localaddr;
localaddr.sin_family = AF_INET;
localaddr.sin_port = htons(PORT);
localaddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
int nBind;
nBind = bind(sock, (struct sockaddr *)&localaddr, sizeof(struct sockaddr_in));
if(nBind == SOCKET_ERROR)
{
printf("bind fail !");
::Sleep(3000);
return ;
}
int nListen;
nListen = listen(sock, MAXLISTEN);
if(nListen == SOCKET_ERROR)
{
std::cout<<"listen fail !"<<std::endl;
::Sleep(3000);
return ;
}
while(true)
{
SOCKET newsocket;
struct sockaddr_in clientaddr;
int length;
length = sizeof(struct sockaddr_in);
newsocket = accept(sock, (struct sockaddr FAR *)&clientaddr, &length);
if(newsocket == INVALID_SOCKET)
{
printf("accept fail !");
::Sleep(3000);
int error = WSAGetLastError();
std::cout<<error<<std::endl;
::Sleep(3000);
break ;
}
//send file
ifstream ofile("write.txt");//读取write.txt里面的文本发送
const int nima= 1024*10;
char buffer[nima]; // = "this is the server !";
ofile.read(buffer,nima);
ofile.close();
char buffer2[nima] = "this is the server !";
int nSend;
nSend = send(newsocket, buffer2, sizeof(buffer2), 0);
if(nSend == SOCKET_ERROR)
{
printf("send fail !");
Sleep(3000);
break ;
}
printf("Send MSG success.");
//
closesocket(newsocket);
}
closesocket(sock);
WSACleanup();
}
// SocketClient.cpp : 定义控制台应用程序的入口点。
//