博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Windows Socket 编程, WIN32_LEAN_AND_MEAN 的用法
阅读量:4181 次
发布时间:2019-05-26

本文共 1813 字,大约阅读时间需要 6 分钟。

一、基本Socket 调用

原文地址:

注意关于windows.h 与 winsock2.h 一起使用时的问题:

The Winsock2.h header file internally includes core elements from theWindows.h header file, so there is not usually an #include line for theWindows.h header file in Winsock applications. If an #include line is needed for theWindows.h header file, this should be preceded with the #define WIN32_LEAN_AND_MEAN macro. For historical reasons, theWindows.h header defaults to including theWinsock.h header file for Windows Sockets 1.1. The declarations in theWinsock.h header file will conflict with the declarations in theWinsock2.h header file required by Windows Sockets 2.0. The WIN32_LEAN_AND_MEAN macro prevents theWinsock.h from being included by theWindows.h header. An example illustrating this is shown below.

#ifndef WIN32_LEAN_AND_MEAN#define WIN32_LEAN_AND_MEAN#endif#include 
#include
#include
#include
#include
#pragma comment(lib, "Ws2_32.lib")int main() { return 0;}

二、高级调用及线程管理

1. 多线程

原文地址: 

A simple echo server:

#include "Socket.h"#include 
#include
unsigned __stdcall Answer(void* a) { Socket* s = (Socket*) a; while (1) { std::string r = s->ReceiveLine(); if (r.empty()) break; s->SendLine(r); } delete s; return 0;}int main(int argc, char* argv[]) { SocketServer in(2000,5); while (1) { Socket* s=in.Accept(); unsigned ret; _beginthreadex(0,0,Answer,(void*) s,0,&ret); } return 0;}

2. 从已建立连接的socket 取得对方IP 地址

SOCKET ClientSocket = accept(ListenSocket, NULL, NULL);	sockaddr_in remoteName;	int  remNameLen=sizeof(remoteName);	memset((void *)& remoteName, 0, remNameLen);	int iResult = getpeername(ClientSocket, (sockaddr *) & remoteName,& remNameLen);	printf("Remote IP: %s\n", inet_ntoa(remoteName.sin_addr));

转载地址:http://rthai.baihongyu.com/

你可能感兴趣的文章
CMake 手册详解(八)
查看>>
CMake手册详解 (九)
查看>>
CMake手册详解 (十)
查看>>
CMake手册详解 (十一)
查看>>
CMake手册详解 (十二)
查看>>
CMake手册详解 (十三)
查看>>
CMake手册详解 (十四)
查看>>
CMake手册详解 (十五)
查看>>
map::lower_bound/upper_bound的使用
查看>>
C++ STL中Map的按Key排序和按Value排序
查看>>
互斥量、条件变量与pthread_cond_wait()函数的使用,详解
查看>>
IO模式设置网络编程常见问题总结
查看>>
windows 编译webrtc 58版本库
查看>>
git tag操作教程
查看>>
Ubuntu系统中git每次提交都要输入密码怎么办?
查看>>
constexpr关键字
查看>>
std::copy详解
查看>>
C++11 新特性摘抄
查看>>
WebRTC学习之函数的异步执行
查看>>
WebRTC 的 PROXY - 如何解决应用中的线程乱入
查看>>