C-socket编程,实现客户端与服务端通信(客户端)

2021-11-27 233 0

#include <cstdio>
#include <Winsock2.h>
#pragma comment(lib,"ws2_32.lib")
int main()
{
	WORD wVersionRequested;
	WSADATA wsaData;
	int err;
	wVersionRequested=MAKEWORD(1,1);
	err=WSAStartup(wVersionRequested,&wsaData);//windows socket启动命令
	if(err!=0)
	{
		return -1;
	}
	//创建socket操作,建立流式套接字,返回套接字号sockClient
	SOCKET sockClient=socket(AF_INET,SOCK_STREAM,0);
	//将套接字sockClient与远程主机想连
	SOCKADDR_IN addrSrv;
	addrSrv.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
	addrSrv.sin_family=AF_INET;
	addrSrv.sin_port=htons(6000);
	connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
	//接受服务器数据
	char recvBuf[100];
	int nRecv=recv(sockClient,recvBuf,100,0);
	//	printf("%s\n",recvBuf);
	//发送数据
	send(sockClient,"Attention:A client has enter...\n",strlen("Attention:A client has enter...\n")+1,0);
	printf("我们可以聊五句话");
	int n=5;
	do
	{
		printf("\n还剩下%d次",n);
		char talk[100];
		printf("\nplease enter what you want to say next(\"quit\"to exit):");
		gets(talk);
		send(sockClient,talk,strlen(talk)+1,0);
		char recvBuf[100];
		recv(sockClient,recvBuf,100,0);
		printf("%s Says:%s\n","server",recvBuf);
	}while(--n);
	printf("ending linking...\n");
	closesocket(sockClient);
	WSACleanup();//终止对套接字的使用
	printf("\n");
	system("pause");
	return 0;
}

相关文章

【转】C++-ADO编程详解
c-各变量在内存中的位置
c-变态跳台阶
C++-编写类String的构造函数、析构函数和赋值函数
c-计蒜客 排序好的数组删除重复数字
c-归并排序

发布评论