socket:client
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <windows.h>
#include <stdio.h>
#include <string.h>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main()
{
WORD ver = MAKEWORD(2, 2);
WSADATA dat;
WSAStartup(ver, &dat);
SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == INVALID_SOCKET) {
printf("创建失败...\n");
}
else {
printf("创建成功...\n");
}
sockaddr_in sin = {};
sin.sin_family = AF_INET;
sin.sin_port = htons(4567);
sin.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
int ret = connect(sock, (sockaddr*)&sin, sizeof(sockaddr_in));
if (ret == SOCKET_ERROR) {
printf(("连接失败....\n"));
}
else {
printf(("连接成功....\n"));
}
char cmdbuf[128];
while (true) {
printf("请输入命令:");
scanf("%s", cmdbuf);
if (0 == strcmp(cmdbuf, "exit")) {
break;
}
else {
send(sock, cmdbuf, strlen(cmdbuf) + 1, 0);
}
char buf[1024] = {};
recv(sock, buf, 1024, 0);
printf("收到的回复:%s", buf);
}
printf("客户端退出,任务结束\n");
getchar();
closesocket(sock);
WSACleanup();
}