您现在的位置:首页 >> 网络通讯 >> 网络通讯 >> 内容

基于WinSocket的单线程Server的实现

时间:2011/9/3 15:14:11 点击:

  核心提示:#include iostream#include 'winsock2.h'#include windows.husing namespace std;int main(){ //启动WS2_32.d...
#include <iostream> #include "winsock2.h" #include <windows.h>   using namespace std;   int main(){      //启动WS2_32.dll      WSADATA wsaData;      int nResult = WSAStartup(MAKEWORD(2,2),&wsaData);      if(nResult != NO_ERROR){          cout << "Error at WSAStartup" << endl;          return 1;      }        //创建一个socket      SOCKET m_socket;      m_socket = socket(AF_INET, //协议族          SOCK_STREAM,           //SOCKET类型          IPPROTO_TCP);          //此socket使用的协议      if(m_socket == INVALID_SOCKET){          cout << "Error at socket " << WSAGetLastError() << endl;          WSACleanup();          return 1;      }        //Bind a socket      sockaddr_in service;      service.sin_family = AF_INET;//协议族      service.sin_addr.s_addr = inet_addr("127.0.0.1");//IP地址      service.sin_port = htons(27002);               //端口号        //将socket与指定的地址绑定      if(bind(m_socket,(SOCKADDR*)&service,sizeof(service)) == SOCKET_ERROR){          cout << "Error at bind " << endl;          closesocket(m_socket);          return 1;      }        //监听socket      if(listen(m_socket,20) == SOCKET_ERROR){          cout << "Error on listen" << endl;           return 1;      }        //接受一个socket连接      SOCKET AcceptSocket;      cout << "Waiting for client to connect" << endl;      while (1) {          AcceptSocket = SOCKET_ERROR;          while (AcceptSocket == SOCKET_ERROR) {               AcceptSocket = accept(m_socket,NULL,NULL);          }            cout << "client connected!" << endl;          m_socket = AcceptSocket;          break;      }        int nSendBytes = 0;      int nRecvBytes = 0;      char pSendBytes[32] = "Server:Send data";      char pRecvBytes[32] = "";        //从socket接收数据.      nRecvBytes = recv(m_socket,pRecvBytes,32,0);      cout << "Num of receive :" << nRecvBytes << endl;      cout << pRecvBytes << endl;        //向socket发送数据。      nSendBytes = send(m_socket,pSendBytes,32,0);      if (nSendBytes == SOCKET_ERROR) {          int nErr = WSAGetLastError();          WSAEACCES;          cout << nErr << endl;      }else         cout <<"Num of send : " << nSendBytes << endl;      //清除WS2_32.dll      Sleep(5000);      WSACleanup();          return 0; }

作者:网络 来源:转载
共有评论 0相关评论
发表我的评论
  • 大名:
  • 内容:
  • 盒子文章 技术支持:深圳市麟瑞科技有限公司(www.2ccc.com) © 2024 版权所有 All Rights Reserved.
  • 粤ICP备10103342号-1