C语言socket模拟客户和服务器通信

客户端代码:

#include <iostream>
#include <winsock2.h>
#include <string>
#define SERVER_PORT 6666
#pragma comment(lib,"ws2_32")
using namespace std;
int main(int agrn,char *agrs[]){
	char server_Ip[30];
	WORD mSocketVersionCode;
	WSADATA wasData;
	SOCKET client_Socket;
	struct sockaddr_in server_addr;
	int return_Num;
	mSocketVersionCode = MAKEWORD(2,2);
	return_Num = WSAStartup(mSocketVersionCode,&wasData);
	if(LOBYTE(wasData.wVersion)!=2||LOBYTE(wasData.wVersion)!=2){
		cout<<"The version of Socket if compaliable"<<endl;
		return -1;

	}
	//创建本地Socket
	client_Socket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
	if(client_Socket == INVALID_SOCKET){
		cout<<"Create Local Socket Failed!"<<endl;
		closesocket(client_Socket);
		return 0; 
	}
	cout<<"Please input the ip of the server!:";
	cin>>server_Ip;
	//构建服务器地址信息 
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = ntohs(SERVER_PORT);
	server_addr.sin_addr.S_un.S_addr = inet_addr(server_Ip);
	//连接服务器
	return_Num = connect(client_Socket,(struct sockaddr*)&server_addr,sizeof(server_addr));
	if(return_Num == SOCKET_ERROR){
		cout<<"Connet Failed"<<endl;
		closesocket(client_Socket);
		WSACleanup();
		return 0;
	}else{
		cout<<"Connect Successfully!"<<endl;
	}
	char buff[1024];
	cout<<"Please input the message to send to the server:";
	cin>&g
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值