首页 > 编程语言 >简单网络编程--TCP SERVER 端

简单网络编程--TCP SERVER 端

时间:2023-06-09 16:34:51浏览次数:31  
标签:__ -- SimpleTcpServer TCP int 简单网络 客户 FILE include


 

一个服务器,接受客户连接,返回客户IP地址,并关闭连接。


一个服务器程序的基本步骤:

1. winsock library 的初始化

2. 创建socket

3. 服务器地址

4. bind->listen

5. 等待客户连接 accept

6. 处理客户接入

7. 关闭 socket

8. 释放资源:winsock library




// SimpleTcpServer.cpp : Defines the entry point for the console application.

//


#include 
"stdafx.h"

#include 
<winsock2.h>

#pragma comment(lib,
"ws2_32"
)

#include 
"SimpleTcpServer.h"


#include 
<conio.h>


#ifdef _DEBUG

#define 
new

 DEBUG_NEW

#undef THIS_FILE

static

 char

 THIS_FILE[] = __FILE__
;
#endif


/

// The one and only application object

//z 2011-05-22 21:23:03@is2120




CWinApp theApp;

using

 namespace

 std;



UINT  ServerThread(LPVOID pParam);

int

 _tmain(int

 argc, TCHAR* argv[], TCHAR* envp[])


{


  int

 nRetCode = 0
;



  // initialize MFC and print and error on failure



  if
 (!AfxWinInit(::GetModuleHandle(NULL
), NULL
, ::GetCommandLine(), 0
))


  {


    // 
TODO

: change error code to suit your needs



    cerr << _T("Fatal Error: MFC initialization failed"
) << endl;


    nRetCode = 1
;


  }


  else



  {


    // 
TODO

: code your application's behavior here.



    /*

    CString strHello;

    strHello.LoadString(IDS_HELLO);

    cout << (LPCTSTR)strHello << endl;

    
*/



    int

 nRetCode = 0
; 


    


    cout << "Press ESCAPE to terminate program
/r/n
"
;


    AfxBeginThread(ServerThread,0
);


    while
(_getch()!=27
);


    


    return

 nRetCode;


  }



  return

 nRetCode;


}



UINT  ServerThread(LPVOID pParam)


{ 


    cout << "Starting up TCP server
/r/n
"
;



    //A SOCKET is simply a typedef for an unsigned int.




    //In Unix, socket handles were just about same as file 




    //handles which were again unsigned ints.




    //Since this cannot be entirely true under Windows




    //a new data type called SOCKET was defined.




    SOCKET server;



    //WSADATA is a struct that is filled up by the call 




    //to WSAStartup




    WSADATA wsaData;



    //The sockaddr_in specifies the address of the socket




    //for TCP/IP sockets. Other protocols use similar structures.




    sockaddr_in local;



    //WSAStartup initializes the program for calling WinSock.




    //The first parameter specifies the highest version of the 




    //WinSock specification, the program is allowed to use.




    int

 wsaret=WSAStartup(0x101
,&wsaData);



    //WSAStartup returns zero on success.




    //If it fails we exit.




    if
(wsaret!=0
)


    {


        return

 0
;


    }



    //Now we populate the sockaddr_in structure




    local.sin_family=AF_INET; //Address family




    local.sin_addr.s_addr=INADDR_ANY; //Wild card IP address




    local.sin_port=htons((u_short)20248
); //port to use




    //the socket function creates our SOCKET




    server=socket(AF_INET,SOCK_STREAM,0
);



    //If the socket() function fails we exit




    if
(server==INVALID_SOCKET)


    {


        return

 0
;


    }



    //bind links the socket we just created with the sockaddr_in 




    //structure. Basically it connects the socket with 




    //the local address and a specified port.




    //If it returns non-zero quit, as this indicates error




    if
(bind(server,(sockaddr*)&local,sizeof
(local))!=0
)


    {


        return

 0
;


    }



    //listen instructs the socket to listen for incoming 




    //connections from clients. The second arg is the backlog




    if
(listen(server,10
)!=0
)


    {


        return

 0
;


    }



    //we will need variables to hold the client socket.




    //thus we declare them here.




    SOCKET client;


    sockaddr_in from;


    int

 fromlen=sizeof
(from);



    while
(true
)//we are looping endlessly




    {


        char

 temp[512
];



        //accept() will accept an incoming




        //client connection




        client=accept(server,


            (struct

 sockaddr*)&from,&fromlen);


    


        sprintf(temp,"Your IP is 
%s
/r/n
"
,inet_ntoa(from.sin_addr));



        //we simply send this string to the client




        send(client,temp,strlen(temp),0
);


        cout << "Connection from "
 << inet_ntoa(from.sin_addr) <<"
/r/n
"
;


    


        //close the client socket




        closesocket(client);



    }



    //closesocket() closes the socket and releases the socket descriptor




    closesocket(server);



    //originally this function probably had some use




    //currently this is just for backward compatibility




    //but it is safer to call it as I still believe some




    //implementations use this to terminate use of WS2_32.DLL 




    WSACleanup();



    return

 0
;


}

标签:__,--,SimpleTcpServer,TCP,int,简单网络,客户,FILE,include
From: https://blog.51cto.com/u_16156420/6449068

相关文章

  • 几个有特点的大学
    河南  河南大学开封     郑州大学 湖南  湖南大学 中南大学      湖南师范大学 湘潭大学湖北  华中农业大学 华中师范大学 华中科技大学    武汉大学  武汉理工大学    中南财经政法大学中国地质大学(武汉) ......
  • 在使用vs2010调试时大量出现iso_whid,HR PROPAGATED 信息
    //z9/5/20112:[email protected]_whid错误在用visualstudio2010调试时会向dbgview输出大量的如下信息:***HRpropagated:-2147024774[8092]*** SourceFile:d:\iso_whid\x86fre\base\isolation\com找了下有以下这些解决方案1.在dbgview中设置过滤器在d......
  • java8如何校验ssh-keygen生成的公私钥
    如果你的公私钥文件不是PEM格式的,而是其他格式,如OpenSSH格式(通常以`id_rsa`和`id_rsa.pub`命名),你可以使用Java的`JSch`库来验证它们的有效性。下面是一个示例代码,演示如何使用`JSch`库验证OpenSSH格式的公私钥对:首先,你需要在项目中引入JSch库的依赖。你可以使用Maven或手动下载并......
  • 不记录最近文档(recent document)
    1.不记录最近文档WindowsRegistryEditorVersion5.00[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer]"NoRecentDocsHistory"=dword:000000012.笔记本cpu功耗性价比anultraportableatnetbook......
  • Solve “missing iconv.dll” issue on Win7 X64
    AfterinstalledthemobilemecontrolpanelonmyWin7X64,themobilemecontrolpanelcannotbelaunchedwitherrormessage"Missingiconv.dll".Evengettingthismessagewhensystembootup.Triedtocopyiconv.dllinto......
  • ubuntu find whereis locate find
     which只能寻找执行文件,并在PATH变量里面寻找。whereis从linux文件数据库(/var/lib/slocate/slocate.db)寻找,所以有可能找到刚刚删除,或者没有发现新建的文件。locate同上,不过文件名是部分匹配。find是直接在硬盘上搜寻,功能强大,但耗硬盘,一般不要用。......
  • 题解 BZOJ4399 魔法少女LJJ
    前言XXX:你瞅你长得那个B样,俺老孙就(氧化钙)......这魔法(J8)少女能不能去死啊啊啊啊啊啊啊啊啊啊......正文"LJJ你是来搞笑的吧"你说得对,但是这数据就是骗人的.首先看题面:然后看样例:最后看数据范围:我惊奇的发现\(c\le7\)!家人们我真难绷qaq...问题分析显......
  • 常见bug测试分类
    常见的BUG包含以下十种类型: 1、业务逻辑 主要的业务流程走不通或出现错误,比如新增保存不成功。 2、功能操作 一些功能按钮无法进行操作,点击按钮没反应。 3、功能优化 功能操作不方便、不合理的地方需要优化。 4、交互逻辑 分为界面交互和功能交互:界面......
  • DevExpress 动态创建实例化类 (xpo)
    使用xpo(devexpress)时动态创建一个持久化类。这样方便访问数据库。/*使用DevExpress控件xpoXPObject持久化对象数据库访问表XPObject*///z2011-07-2722:06:[email protected]转载请注明出处classProgram{staticvoidMain(string[]args){XpoD......
  • BS和CS
    BS和CSCS:客户端服务器架构模式优点:充分利用客户端机器的资源,减轻服务器的负荷(一部分安全要求不高的计算任务存储任务放在客户端执行,从而能够减轻服务器的压力,也能够减轻网络负荷);缺点:需要安装;升级维护成本较高;BS:浏览器服务器架构模式优点:客户端不需要安装;维护成本较低;缺......