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
| #include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <winsock.h>
#pragma comment(lib, "ws2_32.lib")
#define OK 0
#define FAIL 1
#define CONNECT_LOST1 2
#define CONNECT_LOST2 3
#define MSG_EMPTY 4
#define SOCKET_FAIL 5
#define MAX_LEN 100
#define PORT 110
#define _HOST "94.100.177.6"
using namespace std;
int SEND(SOCKET, char*);
int RECV(SOCKET, char*);
int _tmain(int argc, _TCHAR* argv[])
{
setlocale(LC_ALL, "Russian");
int ans = -5;
char GET_MSG[1024];
WSAData WSData;
WSAStartup(0x101,&WSData);
SOCKET S = socket(AF_INET,SOCK_STREAM,0);
sockaddr_in SA;
SA.sin_family=AF_INET;
SA.sin_port=htons(PORT);
SA.sin_addr.S_un.S_addr=inet_addr(_HOST);
connect(S,(sockaddr*)&SA,sizeof(SA));
char SEND_MSG[1024];
string quit = "QUIT";
while(1){
cout << "->";
strcpy(SEND_MSG,"");
strcpy(GET_MSG, "");
scanf("%s", SEND_MSG);
ans = SEND(S, SEND_MSG);
switch(ans){
case FAIL: cout << "Server connection failed\n"; break;
case MSG_EMPTY: cout << "Message is empty\n"; break;
case CONNECT_LOST1: cout << "Server get empty message...\n"; break;
case CONNECT_LOST2: cout << "Server connection lost...\n"; break;
case OK:
printf(GET_MSG);
printf("\n");
break;
}
strcpy(SEND_MSG,"");
strcpy(GET_MSG, "");
scanf("%s", SEND_MSG);
ans1 = RECV(S, GET_MSG);
switch(ans){
case FAIL: cout << "Server connection failed\n"; break;
case MSG_EMPTY: cout << "Message is empty\n"; break;
case CONNECT_LOST1: cout << "Server send empty message...\n"; break;
case CONNECT_LOST2: cout << "Server connection lost...\n"; break;
case OK:
printf(GET_MSG);
printf("\n");
break;
}
}
closesocket(S);
WSACleanup();
cin.get();
system("pause");
return 0;
}
int SEND(SOCKET S,char* msg) {
if(S == INVALID_SOCKET) return SOCKET_FAIL;
if(S == NULL) return FAIL;
if(strlen(msg) == 0) return MSG_EMPTY;
int is_send;
if( (is_send = send(S, msg, sizeof(msg),MSG_DONTROUTE)) < 0)
return CONNECT_LOST2;
return OK;
}
int RECV(SOCKET S, char* msg) {
if(S == INVALID_SOCKET) return SOCKET_FAIL;
if(S == NULL) return FAIL;
int read_bytes;
if( (read_bytes = recvfrom(S, msg, sizeof(msg), 0, NULL, NULL)) < 0)
return CONNECT_LOST2;
if(read_bytes == 0) return MSG_EMPTY;
msg[ read_bytes ] = '\0';
return OK;
} |