赞
踩
步骤如下:
服务器:
1.初始化
包含Winsock2.h头文件和引用ws2_32.lib静态库。
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
WSAStartUp函数
2.创建侦听套接字
3.绑定ip和端口,绑定侦听套接字
SOCKADDR_IN
bind
4.开启监听
listen
5.等待客户端连接
accept
6.收发数据
recv/send
客户端:
1.初始化
包含Winsock2.h头文件和引用ws2_32.lib静态库。
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
WSAStartUp函数
2.创建连接套接字
socket
3.地址解析并连接服务器
SOCKADDR_IN
connect
4.收发数据
recv/send
-------------------------Code----------------------------------------
服务器代码如下:
#include "stdafx.h"
#include <WinSock2.h>
#include <WS2tcpip.h>
#pragma comment(lib,"ws2_32.lib")
#include <stdio.h>
int main()
{
/// 初始化socket
WSADATA wsaData;
WORD version = MAKEWORD(2,2);
int result = 0;
result = WSAStartup(version, &wsaData);
if (0 != result)
{
std::cout << "WSAStartup() error." << std::endl;
return -1;
}
/// 创建侦听socket
SOCKET socketListen;
socketListen = socket(AF_INET, SOCK_STREAM, 0);
if (socketListen == INVALID_SOCKET)
{
WSACleanup();
std::cout << "socket() error." << std::endl;
return -1;
}
/// 服务器地址结构
sockaddr_in svrAddress;
svrAddress.sin_family = AF_INET;
svrAddress.sin_addr.s_addr = INADDR_ANY;
svrAddress.sin_port = htons(8000);
/// 绑定服务器套接字
result = bind(socketListen, (sockaddr*)&svrAddress, sizeof(svrAddress));
if (result == SOCKET_ERROR)
{
closesocket(socketListen);
WSACleanup();
std::cout << "bind() error." << std::endl;
return -1;
}
/// 开启监听
result = listen(socketListen, 5);
if (result == SOCKET_ERROR)
{
closesocket(socketListen);
WSACleanup(); <
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。