码迷,mamicode.com
首页 > 编程语言 > 详细

C语言Socket网络编程实例

时间:2016-05-25 01:48:39      阅读:1250      评论:0      收藏:0      [点我收藏+]

标签:

转自:http://www.cnblogs.com/huxc/p/4272940.html

服务端:

#define _CRT_SECURE_NO_WARNINGS

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

/*
TCP服务端
*/
int main(void)
{
	int len = 0;
	WSADATA         wd;
	int ret = 0;
	SOCKET s, c;
	char sendBuf[1000] = "", recvBuf[1000] = "";
	SOCKADDR_IN saddr, caddr;
	ret = WSAStartup(MAKEWORD(2, 2), &wd);  /*1.初始化操作*/

	if (ret != 0)
	{
		return 0;
	}
	if (HIBYTE(wd.wVersion) != 2 || LOBYTE(wd.wVersion) != 2)
	{
		printf("初始化失败");
		WSACleanup();
		return 1;
	}

	/*2.创建服务端socket*/
	s = socket(AF_INET, SOCK_STREAM, 0);

	/*3.设置服务端信息*/
	saddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
	saddr.sin_family = AF_INET; /*协议类型*/
	saddr.sin_port = htons(8888);

	/*4.绑定在本地端口*/
	bind(s, (SOCKADDR *)&saddr, sizeof(SOCKADDR));

	/*5.监听端口*/
	listen(s, 5);

	len = sizeof(SOCKADDR);

	while (1)
	{
		/*6.等待客户端连接,会阻塞在此处,直到有客户端连接到来。*/
		c = accept(s, (SOCKADDR*)&caddr, &len);

		sprintf(sendBuf, "欢迎来到我的第一个socket,您的ip地址为:%s\n", inet_ntoa(caddr.sin_addr));

		/*7.发送数据到客户端*/
		send(c, sendBuf, strlen(sendBuf) + 1, 0);

		/*8.接受客户端的返回*/
		recv(c, recvBuf, 1000, 0);

		/*9.打印出客户端发送来的数据*/
		printf("%s\n", recvBuf);

		/*10.如果不再跟这个客户端联系,就关闭它*/
		closesocket(c);
	}
	/*如果有退出循环的条件,这里还需要清除对socket库的使用*/
	/* WSACleanup();*/
	return 0;
}

  客户端:

#define _CRT_SECURE_NO_WARNINGS

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

int main(void)
{
	WSADATA         wd;
	int ret = 0;
	SOCKET c;
	char recvBuf[1000] = "", sendBuf[1000] = "";
	SOCKADDR_IN saddr;
	ret = WSAStartup(MAKEWORD(2, 2), &wd);  /*1.初始化操作*/

	if (ret != 0)
	{
		return 0;
	}

	if (HIBYTE(wd.wVersion) != 2 || LOBYTE(wd.wVersion) != 2)
	{
		printf("初始化失败");
		WSACleanup();
		return 1;
	}

	/*2.创建客户端socket*/
	c = socket(AF_INET, SOCK_STREAM, 0);

	/*3.定义要连接的服务端信息*/
	saddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
	saddr.sin_family = AF_INET;
	saddr.sin_port = htons(8888);

	/*4.连接服务端*/
	connect(c, (SOCKADDR*)&saddr, sizeof(SOCKADDR));
	recv(c, recvBuf, 1000, 0);
	printf("服务端发来的数据:%s\n", recvBuf);

	sprintf(sendBuf, "服务端你好!!!");
	send(c, sendBuf, strlen(sendBuf) + 1, 0);

	closesocket(c);
	WSACleanup();

	getchar();
	return 0;
}

  

C语言Socket网络编程实例

标签:

原文地址:http://www.cnblogs.com/199qiang/p/5525577.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!