#include
"stdafx.h"
#include
<WinSock2.h>
#include
<string>
#include
<iostream>
#pragma
comment
(
lib
,
"WS2_32.lib"
)
const
static
int
_MAX_BUF_SIZE
= 256;
using
namespace
std
;
int
_tmain
(
int
argc
,
_TCHAR
*
argv
[])
{
WSADATA
wsaData
;
if
(
WSAStartup
(
MAKEWORD
( 2, 2 ), &
wsaData
) != 0 )
{
cout
<<
"WSAStartup
无法初始化
!"
<<
endl
;
return
-1;
}
SOCKET
sHost
;
sHost
=
socket
(
AF_INET
,
SOCK_STREAM
,
IPPROTO_TCP
);
if
(
INVALID_SOCKET
==
sHost
)
{
cout
<<
"socket failed !"
<<
endl
;
WSACleanup
();
return
-1;
}
SOCKADDR_IN
servAddr
;
servAddr
.
sin_family
=
AF_INET
;
servAddr
.
sin_addr
.
S_un
.
S_addr
=
inet_addr
(
"192.168.1.44"
);
servAddr
.
sin_port
=
htons
(9990);
int
sServerAddrLen
=
sizeof
(
servAddr
);
int
retVal
;
retVal
=
connect
(
sHost
, (
LPSOCKADDR
)&
servAddr
,
sizeof
(
servAddr
) );
if
(
SOCKET_ERROR
==
retVal
)
{
cout
<<
"connect failed !"
<<
endl
;
closesocket
(
sHost
);
WSACleanup
();
return
-1;
}
char
buf
[
_MAX_BUF_SIZE
];
while
(1)
{
cout
<<
"Please input a string to send:"
<<
endl
;
std
::
string
str
;
std
::
getline
(
std
::
cin
,
str
);
ZeroMemory
(
buf
,
_MAX_BUF_SIZE
);
strcpy
(
buf
,
str
.
c_str
() );
retVal
=
send
(
sHost
,
buf
,
strlen
(
buf
), 0 );
if
(
SOCKET_ERROR
==
retVal
)
{
cout
<<
"send failed!"
<<
endl
;
closesocket
(
sHost
);
WSACleanup
();
return
-1;
}
retVal
=
recv
(
sHost
,
buf
,
sizeof
(
buf
) + 1, 0 );
cout
<<
"Recv From Server: %s "
<<
buf
<<
endl
;
if
(
strcmp
(
buf
,
"quit"
) == 0 )
{
cout
<<
"quit!"
<<
endl
;
break
;
}
}
closesocket
(
sHost
);
WSACleanup
();
system
(
"pause"
);
return
0;
}