#include<iostream>
#include<stdio.h>
#include<winsock2.h>
#pragma comment(lib,"ws2_32.lib")
#define PORT 9624
using namespace std;
int main()
{
//初始化
WSADATA wsaData;
WORD sockVersion=MAKEWORD(2,2);
if(WSAStartup(sockVersion,&wsaData)!=0)
{
cout<<"start OK!"<<endl;
return 0;
}
//create a socket
SOCKET sDnf=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(sDnf==INVALID_SOCKET)
cout<<"SOCKET CREATE ERROR!"<<endl;
//load address to socket
sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(PORT);
sin.sin_addr.s_addr=inet_addr("183.99.121.27");
sin.sin_addr.S_un.S_addr=ADDR_ANY;
//bind socket to local address
if(bind(sDnf,(LPSOCKADDR)&sin,sizeof(sin))==SOCKET_ERROR)
{
cout<<"bind error!"<<endl;
closesocket(sDnf);
return 0;
}
//set socket to listen
if(listen(sDnf,15)==SOCKET_ERROR)
{
cout<<"listen error!"<<endl;
closesocket(sDnf);
return 0;
}
//loop for accepting the socket
sockaddr_in remoteAddr;
SOCKET sDnfClient;
int nAddrLen=sizeof(remoteAddr);
char *buff_1="ok|TestLoginOk|1442d9882f6cf8a988bb5c69eeac7d2b1e2931021427d98e2f1df8b488bb5c18eede7d2e1e4f3165|2010-06-28 12:00:00";
char *buff_2="00000";
char *buff_3="0x45 0x00 0x00 0x28 0x3B 0x3D 0x40 0x00 0x75 0x06 0x12 0xBF 0xAE 0x24 0x48 0xA2 0xC0 0xA8 0x00 0x65 0x25 0x96 0x09 0x5F 0xED 0x4E 0x8C 0x58 0x23 0xB1 0x99 0x8B 0x50 0x14 0x00 0x00 0x92 0x23 0x00 0x00 0xED 0x4E 0x8C 0x58 0x23 0xB1 0x99 0x8B";
int nCount=0;
char revData[255];
cout<<"begin to wait!"<<endl;
while(1)
{
//acceot a socket
sDnfClient=accept(sDnf,(LPSOCKADDR)&remoteAddr,&nAddrLen);
//if calling accpet() failed,then return to the head
if(sDnfClient==INVALID_SOCKET)
{
cout<<"accept error!"<<endl;
continue;
}
else
cout<<"accept OK!"<<endl<<inet_ntoa(remoteAddr.sin_addr)<<endl;//print the ip connected
//print data until receive
int ret=recv(sDnfClient,revData,255,0);
if(ret>0)
{
//in order to prevent mistake,set the end 0x00
revData[ret]=0x00;
cout<<revData<<endl;
nCount=nCount+1;
}
cout<<nCount<<endl;
send(sDnfClient,buff_1,strlen(buff_1),0);
switch(nCount)
{
case 2: send(sDnfClient,buff_1,strlen(buff_1),0);
case 3: send(sDnfClient,buff_2,strlen(buff_2),0);
case 5: send(sDnfClient,buff_3,strlen(buff_3),0);
}
closesocket(sDnfClient);
cout<<"OK";
}
closesocket(sDnf);
WSACleanup();
return 0;
}
这是自己先学先写的SERVER,安装loopback adapter,设置虚拟地址为183.99.121.27,然后开启程序,抓包显示183.99.121.27(客户端),183.99.121.27(服务端),而且,服务端一直停留在,“begin to wait”,也就是它没有接到封包。。自己发给自己,杯具。。。我尝试写了一个client,可同样不行。
望高手解决一下!!
[注意]传递专业知识、拓宽行业人脉——看雪讲师团队等你加入!