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

2023-03-03 19:30:45 浏览数 (1)

浏览量 1

代码语言:javascript复制
#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("%sn",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:%sn","server",recvBuf);
	}while(--n);
	printf("ending linking...n");
	closesocket(sockClient);
	WSACleanup();//终止对套接字的使用
	printf("n");
	system("pause");
	return 0;
}

0 人点赞