先看服务端:
// ConsoleApplication3.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#define _WINSOCK_DEPRECATED_NO_WARNINGS //这个声明要在stdafx.h的后面,但要在其他头文件的前面
#include <winsock2.h>
#include <stdio.h>
#include <windows.h>
// 需要声明Winsock库
#pragma comment(lib, "Ws2_32.lib")
int _tmain(int argc, _TCHAR* argv[])
{
//----------------------
// 此时ws2_32.dll可能还没有加载,需要用WSAStartup确认已经完成了加载
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2),&wsaData);
if (iResult != NO_ERROR) {
wprintf(L"WSAStartup failed with error: %ld\n", iResult);
return 1;
}
//----------------------
// 创建一个套接字用于监听客户端连接的请求
SOCKET ListenSocket;
// 参数一:使用IPv4地址
// 参数二:Socket支持可靠、双向的连接
// 参数三:Winsock支持多种网络协议,这里使用TCP协议
ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ListenSocket == INVALID_SOCKET) {
wprintf(L"socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
//----------------------
// 给套接字绑定端口和ip
// 在IPv4下sockaddr_in、SOCKADDR_IN、sockaddr、SOCKADDR可以通用
sockaddr_in service;
service.sin_family = AF_INET;
// inet_addr()将点十进制转换成无符号长整型,也就是in_addr,还有个inet_ntoa函数可以
// 传入一个in_addr将其转为点十进制
service.sin_addr.s_addr = inet_addr("127.0.0.1");
//htons主机字节转为网络字节,传入u_short,htonsl传入u_long,ntohs和ntohl是这个函数的逆运算
service.sin_port = htons(12000);
if (bind(ListenSocket,
(SOCKADDR *)service, sizeof(service)) == SOCKET_ERROR) {
wprintf(L"bind failed with error: %ld\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
//----------------------
// 监听客户端请求
if (listen(ListenSocket, 1) == SOCKET_ERROR) {
wprintf(L"listen failed with error: %ld\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
SOCKET AcceptSocket;
wprintf(L"Waiting for client to connect...\n");
//----------------------
// 接收客户端的请求
AcceptSocket = accept(ListenSocket, NULL, NULL);
if (AcceptSocket == INVALID_SOCKET) {
wprintf(L"accept failed with error: %ld\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
else
wprintf(L"Client connected.\n");
closesocket(ListenSocket);
WSACleanup();
return 0;
再看客户端:
// ConsoleApplication2.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#define _WINSOCK_DEPRECATED_NO_WARNINGS //使用被弃用函数不警告,位置必须在stdafx.h的后面,在其他头文件的前面
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
// 需要声明Winsock库
#pragma comment(lib, "ws2_32.lib")
int wmain()
{
//----------------------
// 初始化Winsock,确保ws2_32.dll可以使用
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR) {
wprintf(L"WSAStartup function failed with error: %d\n", iResult);
return 1;
}
//----------------------
// 创建一个套接字用于连接服务器
SOCKET ConnectSocket;
// 参数一:使用IPv4地址
// 参数二:Socket支持可靠、双向的连接
// 参数三:Winsock支持多种网络协议,这里使用TCP协议
ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ConnectSocket == INVALID_SOCKET) {
wprintf(L"socket function failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
//----------------------
// 给套接字绑定端口和ip
sockaddr_in clientService;
clientService.sin_family = AF_INET;
clientService.sin_addr.s_addr = inet_addr("127.0.0.1");
clientService.sin_port = htons(12000);
//----------------------
// 连接到服务器
iResult = connect(ConnectSocket, (SOCKADDR *)&clientService, sizeof(clientService));
if (iResult == SOCKET_ERROR) {
wprintf(L"connect function failed with error: %ld\n", WSAGetLastError());
iResult = closesocket(ConnectSocket);
if (iResult == SOCKET_ERROR)
wprintf(L"closesocket function failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
wprintf(L"Connected to server.\n");
iResult = closesocket(ConnectSocket);
if (iResult == SOCKET_ERROR) {
wprintf(L"closesocket function failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
WSACleanup();
return 0;
在上面的服务器和客户端代码的基础上,我们来添加发送和接收TCP消息的代码。服务器和客户端连接成功以后就可以进行发送和接收TCP消息了,为了减少文章篇幅,只贴上新增加的代码。
char *sendbuf = "test from server";
int recvbuflen = 512;
char recvbuf[512];
// 将缓冲区置0,防止字符串出现“烫”
memset(recvbuf, 0, 512);
//----------------------
// 发送数据
iResult = send(AcceptSocket, sendbuf, (int)strlen(sendbuf), 0);
if (iResult == SOCKET_ERROR)
{
printf("send failed with error %d\n", WSAGetLastError());
closesocket(AcceptSocket);
WSACleanup();
return 1;
}
printf("Bytes Sent:%d %s \n", iResult,sendbuf);
//----------------------
// 当没有要发送的数据时关闭连接
iResult = shutdown(AcceptSocket, SD_SEND);
if (iResult == SOCKET_ERROR)
{
printf("shutdown failed with error:%d\n", WSAGetLastError());
closesocket(AcceptSocket);
WSACleanup();
return 1;
}
//----------------------
// 接收数据
do
{
// 如果连接已经关闭,iResult为0
iResult = recv(AcceptSocket, recvbuf, recvbuflen, 0);
if (iResult != 0)
printf("Bytes received:%d %s\n", iResult, recvbuf);
else if (iResult == 0)
printf("Connection closed\n");
else
printf("recv failed with error %d\n", WSAGetLastError());
} while (iResult != 0);
重点说一下recv()这个函数,如果协议栈中的数据小于recv()接收的缓冲区,recv()会直接接收所有的数据,如果协议栈中的数据大于接收的缓冲区,那么会将recv()接收的缓冲区填满,然后再接着接收,如果协议栈中没有数据recv()会一直等待。