客户端
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <WinSock2.h> #pragma comment(lib, "ws2_32.lib") //加载 ws2_32.dll int main(){ FILE*p = fopen("C:\\Users\\Administrator\\Desktop\\1.PNG","rb+"); if (!p)return 0; WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); //创建套接字 SOCKET sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); //向服务器发起请求 sockaddr_in sockAddr; memset(&sockAddr, 0, sizeof(sockAddr)); //每个字节都用0填充 sockAddr.sin_family = PF_INET; sockAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); sockAddr.sin_port = htons(1234); connect(sock, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR)); //接收服务器传回的数据 char szBuffer[MAXBYTE] = { 0 }; char test[100] = "abc"; int readcount = 0; recv(sock, szBuffer, MAXBYTE, NULL); printf("Message form server: %s\n", szBuffer); while ((readcount=fread(test, 1, 99, p))>0) { send(sock, test, readcount, NULL); //printf("已发送:%s\n", test); } //recv(sock, szBuffer, MAXBYTE, NULL); //printf("Message form server: %s\n", szBuffer); shutdown(sock, SD_SEND);//置于内部 //关闭套接字 //终止使用 DLL WSACleanup(); system("pause"); return 0; }
服务器端
#include <stdio.h>
#include <winsock2.h>
#pragma comment (lib, "ws2_32.lib") //加载 ws2_32.dll
#define BUF_SIZE 100
int main(){
FILE*p = fopen("C:\\Users\\Administrator\\Desktop\\recept.PNG", "wb+");
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
//创建套接字
SOCKET servSock = socket(AF_INET, SOCK_STREAM, 0);
//绑定套接字
sockaddr_in sockAddr;
memset(&sockAddr, 0, sizeof(sockAddr)); //每个字节都用0填充
sockAddr.sin_family = PF_INET; //使用IPv4地址
sockAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); //具体的IP地址
sockAddr.sin_port = htons(1234); //端口
bind(servSock, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR));
//进入监听状态
listen(servSock, 1000);
//接收客户端请求
SOCKADDR clntAddr;
int nSize = sizeof(SOCKADDR);
char buffer[BUF_SIZE] = { 0 }; //缓冲区
int len;
//while (1)
SOCKET clntSock = accept(servSock, (SOCKADDR*)&clntAddr, &nSize);
send(clntSock, "输出开始!", 20, 0);
while ((len = recv(clntSock, buffer, BUF_SIZE-1, NULL))>0)//避免服务器和客户端在同一时间段,同时recv
{
//send(clntSock, buffer, BUF_SIZE, NULL);
fwrite(buffer, 1, len, p);
memset(buffer, 0, BUF_SIZE);
}
//关闭套接字
closesocket(servSock);
//终止 DLL 的使用
WSACleanup();
system("pause");
return 0;
}