-
Notifications
You must be signed in to change notification settings - Fork 1
/
SocketClient.cpp
107 lines (102 loc) · 2.93 KB
/
SocketClient.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// Client.cpp : Defines the entry point for the console application.
//??????????
//1.????? Winsock??
//2.????????????(socket()????)
//3.??§Õ?????????????????
//4.???????????????(connect()????)
//5.????recv()?????????????????,send()???????????????????
//#include "stdafx.h"
#include <iostream>
#include <WinSock2.h>
using namespace std;
#pragma comment(lib, "WS2_32.lib")
//???????WS2_32.lib?????
//#define PORT 12306
int main()
{
SOCKET sock_client;
struct sockaddr_in server_addr;
int addr_len = sizeof(struct sockaddr_in);
char msgbuffer[1000];
memset(msgbuffer, 0, sizeof(msgbuffer));
// ????? winsock2.dll[12/27/2017 MagicScaring]
WSADATA wsaData;
WORD wVersionRequested = MAKEWORD(2, 2); //????·Ú??
if (WSAStartup(wVersionRequested, &wsaData) != 0)
{
cout << "???? winsock.dll???" << endl;
return 0;
}
// ????????? [12/27/2017 MagicScaring]
if ((sock_client = socket(AF_INET, SOCK_STREAM, 0)) == SOCKET_ERROR)
{
cout << "????????????! ???????:" << WSAGetLastError() << endl;
WSACleanup(); //???WinSock????????
return 0;
}
// ??§Õ????????? [12/27/2017 MagicScaring]
//char IP[20] = { "192.168.5.38" };
char IP[20];
cout << "????????????:" << endl;
cin >> IP;
int PORT=0;
cout << "???????:" << endl;
cin >> PORT;
memset((void*)&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = inet_addr(IP);
// ??????????????? [12/27/2017 MagicScaring]
if (connect(sock_client, (struct sockaddr*)&server_addr, addr_len) == SOCKET_ERROR)
{
cout << "???????! ???????:" << WSAGetLastError() << endl;
closesocket(sock_client);
WSACleanup();
return 0;
}
while (true)
{
int sizes;
if ((sizes = recv(sock_client, msgbuffer, sizeof(msgbuffer), 0)) == SOCKET_ERROR)
{
cout << "??????????? ???????" << WSAGetLastError() << endl;
closesocket(sock_client);
WSACleanup();
return 0;
}
else if (sizes == 0)
{
cout << "???????????" << endl;
closesocket(sock_client);
WSACleanup();
return 0;
}
else
{
cout << "The message from Server:" << msgbuffer << endl;
}
while(1)
{
//char send_msg[1000] = { "Hello server" };
char send_msg[1000];
cout << "??????????:" << endl;
cin >> send_msg;
if((sizes = send(sock_client, send_msg, sizeof(send_msg),0)) == SOCKET_ERROR)
{
cout << "??????????! ???????:" << WSAGetLastError() << endl;
}
else if (sizes == 0)
{
cout << "???????????" << endl;
}
else
{
cout << "?????????" << endl;
sizes=0;
}
}
}
closesocket(sock_client);
WSACleanup();
return 0;
}