服务端代码
// Socket_connection.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#ifndef UNICODE
#define UNICODE
#endif
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <Ws2tcpip.h>
#include <stdio.h>
#include <iostream>
#define DEFAULT_BUFLEN 512
// Link with ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")
using namespace std;
void main()
{
//Initialze winsock
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
std::cout << "Can't Initialize winsock!Quiting!" << std::endl;;
return;
}
//Creste a sockrt
SOCKET sockSrv = socket(AF_INET, SOCK_STREAM, 0);
if (sockSrv == INVALID_SOCKET) {
wprintf(L"Can't create a socket with error %d\n", WSAGetLastError());
WSACleanup();
return;
}
//Bind the socket to an ip address and port
int port = 5099;
SOCKADDR_IN addrSrv;
addrSrv.sin_family = AF_INET;
addrSrv.sin_port = htons(port); //1024以上的端口号
addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
//Bind the socket
int retVal = bind(sockSrv, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR));
if (retVal == SOCKET_ERROR) {
printf("Failed bind:%d\n", WSAGetLastError());
closesocket(sockSrv);
WSACleanup();
return;
}
else {
std::cout << "Bind returned success" << std::endl;
}
//Tell winsock the socket is for listening
if (listen(sockSrv, SOMAXCONN) == SOCKET_ERROR) {
printf("Listen failed:%d", WSAGetLastError());
return;
}
//wait for a connection
SOCKADDR_IN addrClient;
int clientSize = sizeof(addrClient);
SOCKET sockConn = accept(sockSrv, (SOCKADDR*)&addrClient, &clientSize);
if (sockConn == SOCKET_ERROR) {
wprintf(L"accept failed with error: %ld\n", WSAGetLastError());
closesocket(sockSrv);
WSACleanup();
return;
}
char host[NI_MAXHOST]; //Client's remote name
char service[NI_MAXSERV]; //Service (i.e. port)the client is connect on
ZeroMemory(host, NI_MAXHOST);//Same as memset(host,0,NI_MAXHOST)
ZeroMemory(service, NI_MAXSERV);
if (getnameinfo((sockaddr*)&addrClient, sizeof(addrClient), host, NI_MAXHOST, service, NI_MAXSERV, 0) == 0) {
std::cout << "connect on port " << service << std::endl;
}
else {
inet_ntop(AF_INET, &addrClient.sin_addr, host, NI_MAXHOST);
std::cout << host << " connect on port " << ntohs(addrClient.sin_port) << std::endl;
}
//while loop:accept and echo message back to client
char recvbuf[DEFAULT_BUFLEN] = "";
int recvbuflen = DEFAULT_BUFLEN;
memset(recvbuf, 0, sizeof(recvbuf));
char sendbuf[] = "Client: sending data test\n";
retVal = send(sockConn, sendbuf, sizeof(sendbuf), 0);
if (retVal == SOCKET_ERROR) {
wprintf(L"send failed with error: %d\n", WSAGetLastError());
closesocket(sockSrv);
WSACleanup();
return;
}
do {
retVal = recv(sockConn, recvbuf, recvbuflen, 0);
if (retVal > 0) {
wprintf(L"Bytes received: %d\n", retVal);
printf("%s\n", recvbuf);
}
else if (retVal == 0)
wprintf(L"Connection closed\n");
else
wprintf(L"recv failed with error: %d\n", WSAGetLastError());
} while (retVal > 0);
closesocket(sockConn);
//close socket
closesocket(sockSrv);
//close winsock
WSACleanup();
system("pause");
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
客户端代码
// socket_client.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#ifndef UNICODE
#define UNICODE
#endif
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <Ws2tcpip.h>
#include <stdio.h>
#include <iostream>
#include <string>
// Link with ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")
using namespace std;
void main()
{
//Initialze winsock
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
std::cout << "Can't Initialize winsock!Quiting!" << std::endl;;
return;
}
//Creste a sockrt
SOCKET sockClient = socket(AF_INET, SOCK_STREAM, 0);
if (sockClient == INVALID_SOCKET) {
wprintf(L"Can't create a socket with error %d\n", WSAGetLastError());
WSACleanup();
return;
}
//Bind the socket to an ip address and port
int port = 5099;
SOCKADDR_IN addrSrv;
addrSrv.sin_family = AF_INET;
addrSrv.sin_port = htons(5099);
//addrSrv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
inet_pton(AF_INET, "127.0.0.1",&addrSrv.sin_addr.S_un.S_addr);
char buff[1024];
memset(buff, 0, sizeof(buff));
//向服务器发出连接请求
if (connect(sockClient, (struct sockaddr*) & addrSrv, sizeof(addrSrv)) == INVALID_SOCKET) {
printf("Connect failed:%d", WSAGetLastError());
return;
}
else
{
//接收数据
recv(sockClient, buff, sizeof(buff), 0);
printf("%s\n", buff);
}
//发送数据
//const char* buffSend = "hello, this is a Client....";
//send(sockClient, buffSend, strlen(buffSend) + 1, 0);
char sendbuf[BUFSIZ];
std::cout << "Use quit to exit!\n";
while (true) {
std::cout << "Please input a string to send:";
std::string str;
getline(std::cin, str);
if (str == "quit") {
break;
}
ZeroMemory(sendbuf, BUFSIZ);
strcpy_s(sendbuf, str.c_str());
if (send(sockClient, sendbuf, strlen(sendbuf) + 1, 0) == SOCKET_ERROR) {
wprintf(L"send failed with error: %d\n", WSAGetLastError());
closesocket(sockClient);
WSACleanup();
break;
}
}
//printf("%d", strlen(buffSend) + 1);
//关闭套接字
closesocket(sockClient);
WSACleanup();
system("pause");
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
演示结果
![](https://i-blog.csdnimg.cn/blog_migrate/5f2efa9aaf0e9f5db75fc1c4c0fb97e0.png)
![](https://i-blog.csdnimg.cn/blog_migrate/1e55aefd2cf804cef8b40347aa55a980.png)
参考链接