Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Winsock simple communication

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

Header file

# include

# include

# include

# include

# include

# pragma comment (lib, "WS2_32.lib")

source code

/ / initialize Winsock

WSADATA wsaData

Int iResult

IResult = WSAStartup (MAKEWORD (2,2), & wsaData)

If (iResult! = 0) {

Printf ("WSAStartup failed:% d\ n", iResult)

Return NULL

}

/ / get connection properties

Struct addrinfo * result = NULL, * ptr = NULL, hints

ZeroMemory (& hints, sizeof (hints))

Hints.ai_family = AF_INET

Hints.ai_socktype = SOCK_STREAM

Hints.ai_protocol = IPPROTO_TCP

IResult = getaddrinfo ("192.168.0.18", "7002", & hints, & result)

/ / iResult = getaddrinfo ("192.168.37.187", "7002", & hints, & result)

If (iResult! = 0) {

Printf ("getaddrinfo failed:% d\ n", iResult)

WSACleanup ()

Return NULL

}

/ / create a Socket object

Ptr = result

SOCKET ConnectSocket = INVALID_SOCKET

ConnectSocket = socket (ptr- > ai_family, ptr- > ai_socktype, ptr- > ai_protocol)

If (ConnectSocket = = INVALID_SOCKET) {

Printf ("Error at socket ():% ld\ n", WSAGetLastError ())

Freeaddrinfo (result)

WSACleanup ()

Return NULL

}

/ / Link

IResult = connect (ConnectSocket, ptr- > ai_addr, (int) ptr- > ai_addrlen)

If (iResult = = SOCKET_ERROR) {

Printf ("Error at socket ():% ld\ n", WSAGetLastError ())

Closesocket (ConnectSocket)

ConnectSocket = INVALID_SOCKET

}

Int nSendBuf = 32 * 1000ram / set to 32K

Setsockopt (ConnectSocket, SOL_SOCKET, SO_RCVTIMEO, (const char*) & nSendBuf, sizeof (int))

/ / Should really try the next address returned by getaddrinfo

/ / if the connect call failed

/ / But for this simple example we just free the resources

/ / returned by getaddrinfo and print an arror message

/ / freeaddrinfo (result)

If (ConnectSocket = = INVALID_SOCKET) {

Printf ("Unable to connect to server!\ n")

WSACleanup ()

Return NULL

}

Send (ConnectSocket, strSendContext.c_str (), strSendContext.length (), 0)

Char szbuffer [1024] = {0}

Recv (ConnectSocket, szbuffer, 1024, 0)

:: closesocket (ConnectSocket)

Description

Current embedded code for automated testing

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report