TCPClient代码
#include <iostream>
#include <winsock2.h>
// Need to link with Ws2_32.lib
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main()
{
//1.加载库
WORD wVersionRequested;
WSADATA wsaData;
int err;
/* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */
wVersionRequested = MAKEWORD(2, 2);
err = WSAStartup(wVersionRequested, &wsaData);
if (err != 0) {
/* Tell the user that we could not find a usable */
/* Winsock DLL. */
printf("WSAStartup failed with error: %d\n", err);
return 1;
}
/* Confirm that the WinSock DLL supports 2.2.*/
/* Note that if the DLL supports versions greater */
/* than 2.2 in addition to 2.2, it will still return */
/* 2.2 in wVersion since that is the version we */
/* requested. */
//验证
if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) {
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
printf("Could not find a usable version of Winsock.dll\n");
WSACleanup();
return 1;
}
else
printf("The Winsock 2.2 dll was found okay\n");
//2.创建套接字(客户端)
SOCKET sockClient = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(INVALID_SOCKET == sockClient)
{
WSACleanup();
return 1;
}
//3.找地方(连接服务器)
sockaddr_in addrServer;
addrServer.sin_family = AF_INET;//地址族
addrServer.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");//服务器地址
addrServer.sin_port = htons(1234);//端口号
if(SOCKET_ERROR == connect(sockClient,(const sockaddr*)&addrServer,sizeof(sockaddr_in)))
{
closesocket(sockClient);
WSACleanup();
return 1;
}
//4.发送数据
char szbuf[100] = {0};
while(1)
{
cin>>szbuf;
send(sockClient,szbuf,sizeof(szbuf),0);
5.接收数据
//int nRel = recv(sockClient,szbuf,sizeof(szbuf),0);
//if(nRel >0)
//{
// cout<<szbuf<<endl;
//}
}
//关闭套接字、卸载库
closesocket(sockClient);
WSACleanup();
system("pause");
return 0;
}