服务端
#include <winsock2.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#pragma comment(lib, "Ws2_32.lib")
void error_handing(const char* message)
{
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
int main(int argc, char* argv[])
{
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
error_handing("WSAStartup() error");
}
SOCKET hServSock, hClntSock;
SOCKADDR_IN servAddr, clntAddr;
int szClntAddr;
char message[] = "hello world!";
if (argc != 2)
{
printf("Usage : %s <port>\n", argv[0]);
exit(1);
}
hServSock = socket(AF_INET, SOCK_STREAM, 0);
if (hServSock == INVALID_SOCKET)
{
error_handing("socket() error");
}
memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
servAddr.sin_port = htons(atoi(argv[1]));
if (bind(hServSock, (SOCKADDR*)&servAddr, sizeof(servAddr)) == SOCKET_ERROR)
{
error_handing("bind() error");
}
if (listen(hServSock, 5) == SOCKET_ERROR)
{
error_handing("listen() error");
}
szClntAddr = sizeof(clntAddr);
hClntSock = accept(hServSock, (SOCKADDR*)&clntAddr, &szClntAddr);
if (hClntSock == INVALID_SOCKET)
{
error_handing("accept() error");
}
closesocket(hClntSock);
closesocket(hServSock);
WSACleanup();
return 0;
}
客户端
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <winsock2.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#pragma comment(lib, "Ws2_32.lib")
void error_handing(const char* message)
{
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
int main(int argc, char* argv[])
{
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
error_handing("WSAStartup() error");
}
SOCKET hSocket;
if (argc != 3)
{
error_handing("argc error");
}
hSocket = socket(AF_INET, SOCK_STREAM, 0);
SOCKADDR_IN servAddr;
memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_addr.S_un.S_addr = inet_addr(argv[1]);
servAddr.sin_port = htons(atoi(argv[2]));
if (connect(hSocket, (SOCKADDR*)&servAddr, sizeof(servAddr)) == SOCKET_ERROR)
{
error_handing("connect error");
}
char message[30];
int strlen = recv(hSocket, message, sizeof(message) - 1, 0);
if (strlen == -1)
{
error_handing("recv error");
}
printf("recv message: %s\n", message);
closesocket(hSocket);
WSACleanup();
return 0;
}
文章来源地址https://www.toymoban.com/news/detail-651605.html
文章来源:https://www.toymoban.com/news/detail-651605.html
到了这里,关于windows Socket简单编程实例的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!