Winsock 入门 Echo 示例

时间:2022-08-25 18:48:35
 #include <stdio.h>
#include <winsock2.h> #pragma comment(lib, "ws2_32") /* WinSock 使用的库函数 */ #define ECHO_DEF_PORT 7 /* 侦听的缺省端口 */
#define ECHO_BUF_SIZE 256 /* 缓冲区的大小 */ int main(int argc, char **argv)
{
WSADATA wsa_data;
SOCKET echo_soc = , /* 侦听 socket 句柄 */
acpt_soc = ; struct sockaddr_in serv_addr, /* socket的本地地址 */
clnt_addr; /* socket的远端地址 */
unsigned short port = ECHO_DEF_PORT;
int result = ;
int addr_len = sizeof(struct sockaddr_in);
char recv_buf[ECHO_BUF_SIZE]; if (argc == )
port = atoi(argv[]); WSAStartup(MAKEWORD(,), &wsa_data);/* 初始化 WinSock资源 */
echo_soc = socket(AF_INET, SOCK_STREAM, ); /* 创建 socket */ /* socket 的本地地址 */
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
serv_addr.sin_addr.s_addr = INADDR_ANY; result = bind(echo_soc, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
if (result == SOCKET_ERROR)
{
printf("[Echo Server] bind error: %d\n", WSAGetLastError());
closesocket(echo_soc);
return -;
} listen(echo_soc, SOMAXCONN); printf("[Echo Server] is running ... ...\n");
while ()
{
acpt_soc = accept(echo_soc, (struct sockaddr *)&clnt_addr, &addr_len);
if (acpt_soc == INVALID_SOCKET)
{
printf("[Echo Server] accept error: %d\n", WSAGetLastError());
break;
} result = recv(acpt_soc, recv_buf, ECHO_BUF_SIZE, );
if (result > )
{
recv_buf[result] = ;
printf("[Echo Server] receives: \"%s\", from %s\r\n",
recv_buf, inet_ntoa(clnt_addr.sin_addr)); result = send(acpt_soc, recv_buf, result, );
} closesocket(acpt_soc);
} closesocket(echo_soc);
WSACleanup(); return ;
}
 #include <stdio.h>
#include <winsock2.h> #pragma comment(lib, "ws2_32") /* WinSock 使用的库函数 */ #define ECHO_DEF_PORT 7 /* 连接的缺省端口 */
#define ECHO_BUF_SIZE 256 /* 缓冲区的大小 */
#define ECHO_DEF_ADD "127.0.0.1"/*连接的默认服务器为本机*/ int main(int argc, char **argv)
{
WSADATA wsa_data;
SOCKET echo_soc = ; /* socket 句柄 */
struct sockaddr_in serv_addr; /* 服务器地址 */
unsigned short port = ECHO_DEF_PORT;
char *conAdd=ECHO_DEF_ADD;
int result = , send_len = ;
char *test_data = "Hello server!", recv_buf[ECHO_BUF_SIZE]; WSAStartup(MAKEWORD(,), &wsa_data);/* 初始化 WinSock资源 */
send_len = strlen(test_data); /* 服务器地址 */
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
serv_addr.sin_addr.s_addr = inet_addr(conAdd); if (serv_addr.sin_addr.s_addr == INADDR_NONE)
{
printf("[ECHO] invalid address\n");
return -;
}; echo_soc = socket(AF_INET, SOCK_STREAM, ); /* 创建 socket */
result = connect(echo_soc, (struct sockaddr *)&serv_addr, sizeof(serv_addr)); if (result == ) /* 连接成功 */
{
result = send(echo_soc, test_data, send_len, );
result = recv(echo_soc, recv_buf, ECHO_BUF_SIZE, );
} if (result > )
{
recv_buf[result] = ;
printf("[Echo Client] receives: \"%s\"\r\n", recv_buf);
}
else
printf("[Echo Client] error : %d.\r\n", WSAGetLastError()); getchar();
closesocket(echo_soc);
WSACleanup(); return ;
}