window下socket实现TCP服务器

服务器

1.初始化
WSAStartup(…)
2.创建Socket
s = Socket ( … )
3.绑定端口
ret = bind ( … )
4.监听
ret = listen ( … )
5.接收客户端的连接请求
s_new = accept ( … ) // 三次握手发生在这个过程
6.收发数据
ret = recv ( … )
// 阻塞模式, 内存不够存放发送的信息时,则阻塞send()
// 非阻塞 , 视缓冲空间大小而发送相应大的数据,不阻塞send()
ret = send ( … )
7.关闭连接

#include

#pragma warning(disable:4996)
#pragma comment(lib,"ws2_32.lib")
#include



int main(int argc, char* argv[])
{
	//请求版本号
	WSADATA wsaData;
	WSAStartup(MAKEWORD(2, 2), &wsaData);

	if (HIBYTE(wsaData.wVersion) != 2 || LOBYTE(wsaData.wVersion) != 2)
	{
		printf("请求版本失败!");
		return -1;
	}
	//创建socket
	SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

	
	//创建协议地址族
	SOCKADDR_IN addr = { 0 };
	addr.sin_family = AF_INET;
	addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
	addr.sin_port = htons(10086);

	//绑定
	int r = bind(serverSocket, (sockaddr*)&addr, sizeof addr);

	//监听
	r = listen(serverSocket, 10);

	//接受客户端连接
	SOCKADDR_IN cAddr = { 0 };
	int size = sizeof cAddr;
	SOCKET clientSocket = accept(serverSocket, (sockaddr*)&cAddr, &size);
	printf("init ok!\n");
	//通信
	char buf[256];
	while (1)
	{
		memset(buf, 0, 256);
		r = recv(clientSocket, buf, 255, NULL);
		if (r > 0)
		{
			printf("来自%s的数据:%s\n", inet_ntoa(cAddr.sin_addr), buf);
		}
		
	}
	//断开连接
	closesocket(clientSocket);
	
	//清楚协议信息
	WSACleanup();
	return  0;


}

客户端
与服务器的区别在于不需要绑定端口
1.初始化
WSAStartup(…)
2.创建Socket
s = Socket ( … )
3.连接服务器
connect(…)
4.收发数据
ret = recv ( … )
// 阻塞模式, 内存不够存放发送的信息时,则阻塞send()
// 非阻塞 , 视缓冲空间大小而发送相应大的数据,不阻塞send()
ret = send ( … )
5.关闭连接

#include
#include
#include
#include
#include

#pragma warning(disable:4996)
#pragma comment(lib,"ws2_32.lib")
#include

int  main(int argc, char* argv[])
{
	//请求版本号
	WSADATA wsaData;
	WSAStartup(MAKEWORD(2, 2), &wsaData);

	if (HIBYTE(wsaData.wVersion) != 2 || LOBYTE(wsaData.wVersion) != 2)
	{
		printf("请求版本失败!");
		return -1;
	}
	//创建socket
	SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

	
	//创建协议地址族
	SOCKADDR_IN addr = { 0 };
	addr.sin_family = AF_INET;
	addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
	addr.sin_port = htons(10086);
	

	//连接
	int r = connect(clientSocket, (sockaddr*)&addr, sizeof addr);
	//通信
	char buf[256];
	while (1)
	{
		printf("请输入发送内容: ");
		scanf("%s", buf);
		r = send(clientSocket, buf, strlen(buf), NULL);
		if (r > 0)
		{
			printf("发送%d字节数据成功\n", r);
		}
	}

}

window下socket实现TCP服务器_第1张图片

你可能感兴趣的:(Windows)