Beginning Winsock Programming - Simple TCP server

Introduction

The WinSock (Windows Sockets) API is a socket programming library for Microsoft Windows Operating Systems. It was originally based on Berkeley sockets. But several Microsoft specific changes were employed. In this article I shall attempt to introduce you to socket programming using WinSock, assuming that you have never done any kind of network programming on any Operating System.

If you only have a single machine, then don't worry. You can still program WinSock. You can use the local loop-back address called localhost with the IP address 127.0.0.1. Thus if you have a TCP server running on your machine, a client program running on the same machine can connect to the server using this loop-back address.

Simple TCP Server

In this article I introduce you to WinSock through a simple TCP server, which we shall create step by step. But before we begin, there are a few things that you must do, so that we are truly ready for starting our WinSock program

  • Initially use the VC++ 6.0 App Wizard to create a Win32 console application. 
  • Remember to set the option to add support for MFC
  • Open the file stdafx.h and add the following line :- #include <winsock2.h>
  • Also #includeconio.h and iostream just after winsock2.h
  • Take Project-Settings-Link and add ws2_32.lib to the library modules list.

The main function

				int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
    int nRetCode = 0;	

    cout << "Press ESCAPE to terminate program\r\n";
    AfxBeginThread(ServerThread,0);
    while(_getch()!=27);

    return nRetCode;
}

What we do in our main() is to start a thread and then loop a call to _getch()_getch() simply waits till a key is pressed and returns the ASCII value of the character read. We loop till a value of 27 is returned, since 27 is the ASCII code for the ESCAPE key. You might be wondering that even if we press ESCAPE, the thread we started would still be active. Don't worry about that at all. When main() returns the process will terminate and the threads started by our main thread will also be abruptly terminated.

The ServerThread function

What I will do now is to list our ServerThread function and use code comments to explain what each relevant line of code does. Basically what our TCP server does is this. It listens on port 20248, which also happens to be my Code Project membership ID. Talk about coincidences. When a client connects, the server will send back a message to the client giving it's IP address and then close the connection and go back to accepting connections on port 20248. It will also print a line on the console where it's running that there was a connection from this particular IP address. All in all, an absolutely useless program, you might be thinking. In fact some of you might even think this is as useless as SNDREC32.EXE which comes with Windows. Cruel of those people I say.

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)
    {
        return0;
    }

    //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 exitif(server==INVALID_SOCKET)
    {
        return0;
    }

    //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 errorif(bind(server,(sockaddr*)&local,sizeof(local))!=0)
    {
        return0;
    }

    //listen instructs the socket to listen for incoming //connections from clients. The second arg is the backlogif(listen(server,10)!=0)
    {
        return0;
    }

    //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();

    return0;
}

Testing it out

Run the server and use telnet to connect to port 20248 of the machine where the server is running. If you have it on the same machine connect to localhost.

Sample Output

We see this output on the server

E:\work\Server\Debug>server
Press ESCAPE to terminate program
Starting up TCP server
Connection from 203.200.100.122
Connection from 127.0.0.1
E:\work\Server\Debug>

And this is what the client gets

nish@sumida:~$ telnet 202.89.211.88 20248
Trying 202.89.211.88...
Connected to 202.89.211.88.
Escape character is '^]'.
Your IP is 203.200.100.122
Connection closed by foreign host.
nish@sumida:~$

Conclusion

Well, in this article you learned how to create a simple TCP server. In further articles I'll show you more stuff you can do with WinSock including creating a proper TCP client among other things. If anyone has problems with compiling the code, mail me and I shall send you a zipped project. Thank you.

About Nishant Sivakumar

 

 Editor
 Site Builder

Nish is a real nice guy living in Toronto who has been coding since 1990, when he was 13 years old. Originally from sunny Trivandrum in India, he has moved to Toronto so he can enjoy the cold winter and get to play in some snow.

He works for The Code Project and is in charge of the MFC libraries Ultimate Toolbox, Ultimate Grid and Ultimate TCP/IP that are sold exclusively through The Code Project Storefront. He frequents the CP discussion forums when he is not coding, reading or writing. Nish hopes to visit at least three dozen countries before his human biological mechanism stops working (euphemism used to avoid the use of the d-word here). Oh btw, it must be mentioned that normally Nish is not inclined to speak about himself in the 3rd person. 

Nish has been a Microsoft Visual C++ MVP since October, 2002 - awfully nice of Microsoft, he thinks. He maintains an MVP tips and tricks web site - www.voidnish.comwhere you can find a consolidated list of his articles, writings and ideas on VC++, MFC, .NET and C++/CLI. Oh, and you might want to check out his blog on C++/CLI, MFC, .NET and a lot of other stuff - blog.voidnish.com

Nish loves reading Science Fiction, P G Wodehouse and Agatha Christie, and also fancies himself to be a decent writer of sorts. He has authored a romantic comedy Summer Love and Some more Cricket as well as a programming book – Extending MFC applications with the .NET Framework.

时间: 2024-09-24 15:38:13

Beginning Winsock Programming - Simple TCP server的相关文章

C# Tutorial - Simple Threaded TCP Server

In this tutorial I'm going to show you how to build a threaded tcp server with C#. If you've ever worked with Window's sockets, you know how difficult this can sometimes be. However, thanks to the .NET framework, making one is a lot easier than it us

Simple Web Server

web服务器hello world!-----简单的socket通信实现. HTTP HTTP是Web浏览器与Web服务器之间通信的标准协议,HTTP指明了客户端如何与服务器建立连接,如果从服务器请求数据,服务器如何响应请求,关闭连接.HTTP是使用TCP/IP协议进行传输数据的,也就是传输层利用TCP进行连接,进行可靠连接的. 详情:点击 请求 一般格式,如: GET /index.html HTTP/1.0 Accept:text/html,text/plain User-Agent: Ly

TCP Server《——》TCP Client

#include <stdio.h> #include <winsock2.h> #pragma comment(lib, "WS2_32") // 链接到WS2_32.lib class CInitSock { public: CInitSock(BYTE minorVer = 2, BYTE majorVer = 2) { // 初始化WS2_32.dll WSADATA wsaData; WORD sockVersion = MAKEWORD(minorV

Simple Rtmp Server的安装与简单使用

Simple Rtmp Server是一个国人编写的开源的RTMP/HLS流媒体服务器. 功能与nginx-rtmp-module类似, 可以实现rtmp/hls的分发.   有关nginx-rtmp-module的可参照: http://blog.csdn.NET/redstarofsleep/article/details/45092147   编译与安装过程十分的简单   [plain] view plain copy    print?   ./configure --prefix=/u

tcp-W5200A工作于TCP Server

问题描述 W5200A工作于TCP Server W5200A工作于TCP Server时,是否支持多个Client同时连接,如果可以,如果判别不同的Client 解决方案 W5200A 是否支持多客户端连接,取决于 Server 程序在实现时指定的最大允许连接数.在看不到其 Server 实现代码的情况下,你只能去试着多终端连接. 判别不同的终端,一般来说是根据终端连接时的 IP 地址.当然,如果有软件协议,另当别论.

A simple IOCP Server/Client Class

  Download demo project v1.13 - 64.4 Kb Download source v1.13 - 121 Kb 1.1 Requirements This article expects the reader to be familiar with C++, TCP/IP, socket programming, MFC, and multithreading. The source code uses Winsock 2.0 and IOCP technology

Multi Libvent TCP Server:一个高性能的TCP服务器

MrioTCP,超级马里奥,顾名思义,他不仅高效,而且超级简易和好玩.同时他可以是一个很简洁的Linux C 开发学习工程.毫不夸张的说,如果全部掌握这一个工程,你会成为一个Linux C的牛人:当然,你也可以通过源码包的mario.c(maritcp服务器示例程序)来学习,可以很快入门上手进行Linux C开发. 经过两个多月的测试(编写c++客户端测试及调优系统参数),测试结果得到单机最大带宽吞吐1000M,测试最高TCP长连接100万,每秒处理连接数达4万,此时系统压力load值很低.总之

1.socket编程:socket编程,网络字节序,函数介绍,IP地址转换函数,sockaddr数据结构,网络套接字函数,socket相关函数,TCP server和client

 1  Socket编程 socket这个词可以表示很多概念: 在TCP/IP协议中,"IP地址+TCP或UDP端口号"唯一标识网络通讯中的一个进程,"IP 地址+端口号"就称为socket. 在TCP协议中,建立连接的两个进程各自有一个socket来标识,那么这两个socket组成的socket pair就唯一标识一个连接.socket本身有"插座"的意思,因此用来描述网络连 接的一对一关系. TCP/IP协议最早在BSD UNIX上实现,

TCP SERVER/CLIENT UDP通讯

问题描述 花了快10天学习了TCPUDP这块的程序,今天终于把UDP和TCPServer端与Client端的程序调试通了.现在把源码分享给需要的朋友!http://pan.baidu.com/s/1nt20VVV程序还有很多可以完善修改的地方,也欢迎大家提出指导意见!分享是为了以后能学习到更多的知识!