上节演示了 Linux 下的 socket 程序,这节来看一下 Windows 下的 socket 程序。一样,server.cpp 为服务器端代码,client 为客户端代码。
服务器端代码 server.cpp:文章源自微观生活(93wg.com)微观生活-https://93wg.com/6304.html
无论你是小白还是大牛,小编我都欢迎进C/C++同享资源群:231662552不按期分享干货,包含我自己收拾的一份2018最新的学习资料以及零基础入门教程,送给大家,欢迎初学以及进阶中的小火伴文章源自微观生活(93wg.com)微观生活-https://93wg.com/6304.html
客户端代码 client.cpp:文章源自微观生活(93wg.com)微观生活-https://93wg.com/6304.html
将 server.cpp 以及 client.cpp 分别编译为 server.exe 以及 client.exe,先运行 server.exe,再运行 client.exe,输出结果为:文章源自微观生活(93wg.com)微观生活-https://93wg.com/6304.html
Message form server: Hello World!文章源自微观生活(93wg.com)微观生活-https://93wg.com/6304.html
Windows 下的 socket 程序以及 Linux 思路相同,但细节有所差别:文章源自微观生活(93wg.com)微观生活-https://93wg.com/6304.html
1) Windows 下的 socket 程序依赖 Winsock.dll 或 ws2_32.dll,必需提早加载。DLL 有两种加载方式文章源自微观生活(93wg.com)微观生活-https://93wg.com/6304.html
2) Linux 使用“文件描写符”的概念,而 Windows 使用“文件句柄”的概念;Linux 不区别 socket 文件以及普通文件,而 Windows 区别;Linux 下 socket 函数的返回值为 int 类型,而 Windows 下为 SOCKET 类型,也就是句柄。文章源自微观生活(93wg.com)微观生活-https://93wg.com/6304.html
3) Linux 下使用 read / write 函数读写,而 Windows 下使用 recv / send 函数发送以及接管。文章源自微观生活(93wg.com)微观生活-https://93wg.com/6304.html
4) 关闭 socket 时,Linux 使用 close 函数,而 Windows 使用 closesocket 函数。文章源自微观生活(93wg.com)微观生活-https://93wg.com/6304.html
以上就是微观生活(93wg.com)关于“一个简单的Windows下的C语言socket程序”的详细内容,希望对大家有所帮助!
评论