-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.cpp
64 lines (58 loc) · 1.25 KB
/
client.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
#include <winsock2.h>
#include <thread>
#include <cstring>
using namespace std;
#pragma comment(lib, "ws2_32.lib")
void receiveMsgFromserver(SOCKET sclient)
{
while (true)
{
string data;
cout << "please input data to server:";
cin >> data;
const char *sendData;
sendData = data.c_str(); // string 转 const char *
send(sclient, sendData, strlen(sendData), 0);
//循环接收数据
char revData[255]; // 保存接收数据
//接收数据
int ret = recv(sclient, revData, 255, 0);
if (ret > 0)
{
revData[ret] = 0x00;
cout << "服务端:";
cout << revData << "\n";
}
}
}
int main()
{
WORD sockVersion = MAKEWORD(2, 2);
WSADATA data;
if (WSAStartup(sockVersion, &data) != 0)
{
return 0;
}
SOCKET sclient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sclient == INVALID_SOCKET)
{
cout << "invalid socket!";
return 0;
}
sockaddr_in serAddr;
serAddr.sin_family = AF_INET;
serAddr.sin_port = htons(8080);
serAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
if (connect(sclient, (sockaddr *)&serAddr, sizeof(serAddr)) == SOCKET_ERROR)
{
cout << "connect error !";
closesocket(sclient);
return 0;
}
thread mes_th(receiveMsgFromserver, sclient);
mes_th.join();
closesocket(sclient);
WSACleanup();
return 0;
}