Getting started with Winsock program (1)

xiaoxiao2021-03-05  20

Author: Nishant S Original link: http: //www.codeproject.com/internet/winsockintro01.asp

First, simple TCP server

Introduction

The Winsock API is a socket library for the Microsoft Windows operating system, which was originally based on the Berkeley socket, but some of the special changes in Microsoft were joined. In this article, I have to try to introduce you how to use Winsock to make socket programming, and assume that you didn't have experience in network programming on any operating system. If you have only a separate machine, then you can still use the Winsock program design. You can use local loopback addresses named localhost, and its IP address is 127.0.0.1. In this way, if you run a TCP server on the machine, the client program on the same machine can be connected to the server using this loop address.

Simple TCP server

In this article, I will introduce you to Winsock through a simple TCP server, and we will create this program step by step. However, before we start, you must do something, so we can prepare for the starting our Winsock programs. · First, use the VC 6.0 Application Wizard to create a Win32 Console Application. · Select the Add Support for MFC option. · Open the stdafx.h file and add this line: #include . · Select Project-Settings-Link and add WS2_32.lib in the library module list.

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 main () is to turn on a thread and then loop a _getch () call. _Getch () is just a button waiting for a key and returns the ASCII value of this read character. We have been loop until 27 this value - Since 27 is the ASCII code of the ESCAPE key. What you might want to know is that even if we press Escape, the thread we open will also be a state of activity. Don't worry for these things, because when main () is returned, the process will be terminated, the thread that the main thread is turned on will also be terminated.

ServerThread function

What I have to do now is to list our ServerThread function and use the code's annotation to explain what the relevant code line is done. Our TCP server mainly doing things is to listen to port 20248, this number is the member ID I am in Code Project. The event in this process is: When the client is connected, the server will send back a message to the client to inform the IP address, then turn off the connection and continue to receive the 20248 port. It also prints an IP address from the connection from the console. All in all, you might think this is an absolutely useless program. In fact, some people in you may even think it is useless as SndRec32.exe in Windows. I said, you are too harsh.

UINT ServerThread (LPVOID PPARAM) {cout << "Starting Up TCP Server / R / N";

// Socket is actually a TypedEf for unsigned int. // In UNIX, the socket handle is like a file handle, is unsigned int. // Since these are not true under Windows, then we define a new data type, named Socket. Socket Server; // WSADATA is a structure, WSAStartup calls will be filled. Wsadata wsadata;

// sockaddr_in specifies the address of the socket for the TCP / IP socket. // Other protocols use similar structures. SockAddr_in local;

// WSAStartup initializes the program call Winsock. // The first parameter specifies the highest version of the Winsock specification allowed by the program. Int wsaret = wsastartup (0x101, & wsadata);

// If successful, WSAStartUp returns zero. // If we fail, we will exit. IF (wsaret! = 0) {return 0;}

// Now let's assign a value for the SockAddr_in structure. Local.sin_family = af_INET; // Address family local.sin_addr.s_addr = INADDR_ANAY; // Grid IP address local.sin_port = htons ((u_short) 20248); // Used ports

// Create our Socket by the Socket function. Server = Socket (AF_INET, SOCK_STREAM, 0);

// If the socket () function fails, we will exit. IF (server == invalid_socket) {return 0;}

// Bind links our sockets and SockAddr_in structures. // It mainly uses local addresses and a specific port to connect sockets. // If it returns a non-zero value, it means an error. IF (Bind (SockAddr *) & local, sizeof (local))! = 0) {return 0;}

// listen command socket monitoring from the client connection. // The second parameter is the maximum number of connections. IF (Listen (Server, 10)! = 0) {RETURN 0;}

/ / We need some variables to save the client's socket, so we are here. SOCKET Client; SockAddr_in from; int.comlen = sizeof (from);

While (True) // Unlimited loop {char Temp [512];

// accept () will receive upcoming client connections. 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 sleeve closesocket (client);

}

// CloseSocket () Close the socket and release the socket descriptor. CloseSocket; // Initially this function may have some use, now keep it just backward compatibility. / / But it may be safer because I believe that some implementations use it to end the use of WS2_32.dll. WSACLEANUP ();

Return 0;}

test

Run this server and use Telnet to connect to the 20248 port of the machine when it runs. If you are using it on the same machine, then connect to localhost.

Example output

We will see such an output on the server:

E: / Work / Server / Debug> ServerPress Escape to Terminate Programstarting Up TCP ServerConnection from 203.200.100.122connection from 127.0.0.1E: / Work / Server / debug>

This is the client get:

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

to sum up

Hey, in this article, you understand how to create a simple TCP server. In future articles, I will give you some more materials, you can create a suitable TCP client through these materials. If anyone can compile these code, you can Mail, I will send you a compressed project. Thank you for reading.

转载请注明原文地址:https://www.9cbs.com/read-38860.html

New Post(0)