最简单的网络编程例子

///
//server
#include <winsock2.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32.lib")

int main()
{
	WSADATA              wsaData;

	int ret = WSAStartup(MAKEWORD(2,2), &wsaData);

	SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	//本地地址信息
	sockaddr_in localAddr;
	localAddr.sin_family = AF_INET;
	localAddr.sin_port = htons(5000);	//本地端口
	localAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");

	if(!bind(s,(sockaddr *)&localAddr,sizeof(sockaddr)))
		printf("bind ok\n");
	//远程主机地址
	sockaddr_in remoteAddr;
	int			remoteAddrLen = sizeof(sockaddr);
	listen(s,5);
	SOCKET remoteSocket;
	while(1)
	{
		remoteSocket = accept(s,(sockaddr *)&remoteAddr,&remoteAddrLen);
		if(remoteSocket!= -1)
		 break;
	}
	
	printf("connection from remote\n");

	char buf[100] = { 0 };
	int bufLen = 100;
	recv(remoteSocket, buf, bufLen, 0);
	printf("%s", buf);

	system("pause");

	return 0;
}

//
//client
/
#include <winsock2.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32.lib")

int main()
{
	WSADATA              wsaData;

	int ret = WSAStartup(MAKEWORD(2,2), &wsaData);


	SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	//本地地址信息
	sockaddr_in localAddr;
	localAddr.sin_family = AF_INET;
	localAddr.sin_port = htons(9999);	//本地端口
	localAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");

	bind(s,(sockaddr *)&localAddr,sizeof(sockaddr));

	//远程主机地址
	sockaddr_in remoteAddr;
	remoteAddr.sin_family = AF_INET;
	remoteAddr.sin_port = htons(5000);		//远程端口
	remoteAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");// 远程IP地址

	ret = connect(s,(sockaddr *)&remoteAddr,sizeof(sockaddr));
	if(!ret) {
		printf("connection ok\n");
	}

	ret = send(s, "hello", 6, 0);
	printf("%d bytes sended\n", ret);

	closesocket(s);

	WSACleanup();

	system("pause");

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值