//第2步:初始化套接口
SOCKET localSendSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP );
if ( localSendSocket == INVALID_SOCKET ) {
printf("error at socket().\n");
return 1;
}
//第3步:绑定本地端口,不绑定也可以,端口会自动分配
sockaddr_in localaddr;
memset(&localaddr, 0, sizeof(localaddr));//全设置成0
localaddr.sin_family = AF_INET;
localaddr.sin_addr.s_addr = htonl(INADDR_ANY);
localaddr.sin_port = htons(5657);
int localaddrSize = sizeof(localaddr);
if(bind( localSendSocket, (sockaddr *)&localaddr, sizeof(struct sockaddr))!=0 ) {
printf("不能绑定端口!\n");//初始化失败返回-1
return -1;
}
//第4步:构造远程socket地址数据结构
sockaddr_in remoteaddr;
memset(&remoteaddr, 0, sizeof(remoteaddr));//全设置成0
remoteaddr.sin_family = AF_INET;
remoteaddr.sin_addr.s_addr = inet_addr( toHostIp );
remoteaddr.sin_port = htons( toHostPort );
if ( connect(localSendSocket, (SOCKADDR*)&remoteaddr, sizeof(struct sockaddr)) == SOCKET_ERROR ) {
AfxMessageBox("connect to server failed.");
}
//此处循环发送20次,但服务器只收到一条数据,不知道怎么处理。
for (int i=0; i<20; i++) {
char* buf = "this is data send to the server!\r\n";
int sendResult = send(localSendSocket, buf, (int)strlen(buf), 0 );
}
//第6步:关闭套接口
closesocket(localSendSocket);
问题已解决,解决办法,在接收程序中添加循环接收。请参看红色部分。
原先的程序只有循环等待连接,也就是"while(true)"部分,而没有“while (n>0)”部分。
谢谢各位!
//等待客户的连接请求
CString fileFullName = "UUTemp/1-test.dat";
while (true) {
SOCKET clientSocket = accept(listenSocket, NULL, NULL);
if (clientSocket == INVALID_SOCKET) {
AfxMessageBox("错误:客户端无效!\n");
nSockErr = WSAGetLastError();
}
else {
//有客户链接请求被成功接收
char buf[2048]; //1024*10
memset(buf, 0, sizeof(char)*2048);
//接收客户端传输过来的数据
int n = recv(clientSocket, buf, 2048, 0);
//循环接收客户端的数据,客户端可能一次连接发送多次数据
while (n>0) { //接收到的文件写入
CString s;
s.Format("服务器已经接收%d个字符:%s\n", n, buf);
//AfxMessageBox(s);
//把接收到的数据写入到文件中
CFile file;
//先判断文件存在不存在,如果不存在,则创建
if( !file.Open(fileFullName, CFile::modeWrite|CFile::typeBinary) ) { //文件不存在
file.Open(fileFullName, CFile::modeCreate|CFile::modeWrite|CFile::typeBinary);
}
else {
//如果文件存在,移动到最后位置
file.SeekToEnd();
}
//往文件中追加数据
file.Write(buf, n);
//关闭文件
file.Close();
n = recv(clientSocket, buf, 2048, 0);
}
//delete []buf;
}
closesocket(clientSocket);
}