socket编程(聊天)

c/s架构

服务器 server 客户端 client

1.请求协议版本 1.请求协议版本

2.创建socket 2.创建socket

3.创建协议地址族 3.获取服务器协议地址族

​ ip地址

​ 网络端口

​ 通信协议

4.绑定

5.监听

6.等待客户端连接 4.连接服务器

7.通信 5.通信

8.关闭socket连接 6.关闭socket

9.清理协议 7.清理协议

客户端和服务器之间通信

一、客户端只能给服务器发送数据,服务器只能接受数据

client.cpp

#include <stdio.h>
#include <stdlib.h>
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
#pragma warning(disable:4996)
int main(void)
{
	// 1 请求协议版本
	WSADATA wsaData;
	WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) {
		printf("请求协议版本失败!\n");
		return -1;
	}
	//2 创建socket
	SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (SOCKET_ERROR == clientSocket) {
		printf("创建socket失败!\n");
		WSACleanup();
		return -2;
	}

	printf("创建socket成功!\n");

	//3 获取协议地址族
	SOCKADDR_IN addr = { 0 };
	addr.sin_family = AF_INET;//协议版本
	addr.sin_addr.S_un.S_addr = inet_addr("192.168.1.9");
	addr.sin_port = htons(10086); // 0-65535
	// os内核和其他程序会占用一些端口

	//4 连接服务器
	int r = connect(clientSocket, (sockaddr*)&addr, sizeof addr);
	if (-1 == r) {
		printf("连接服务器失败!\n");
		return -1;
	}
	printf("连接服务器成功!\n");

	//5 通信
	char buff[1024];
	while (1) {
		memset(buff, 0, 1024);
		printf("你想说啥:");
		scanf("%s", buff);
		send(clientSocket, buff, strlen(buff), NULL);
	}
}

server.cpp

#include <stdio.h>
#include <stdlib.h>
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
#pragma warning(disable:4996)
int main(void)
{	
	// 1 请求协议版本
	WSADATA wsaData;
	WSAStartup(MAKEWORD(2,2),&wsaData);
	if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) {
		printf("请求协议版本失败!\n");
		return -1;
	}
	//2 创建socket
	SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (SOCKET_ERROR == serverSocket) {
		printf("创建socket失败!\n");
		WSACleanup();
		return -2;
	}

	printf("创建socket成功!\n");

	//3 创建协议地址族
	SOCKADDR_IN addr = { 0 };
	addr.sin_family = AF_INET;//协议版本
	addr.sin_addr.S_un.S_addr = inet_addr("192.168.1.9"); 
	addr.sin_port = htons(10086); // 0-65535
	// os内核和其他程序会占用一些端口

	//4 绑定
	int r = bind(serverSocket, (sockaddr*)&addr, sizeof addr);
	if (-1 == r) {
		printf("bind失败!\n");
		closesocket(serverSocket);
		WSACleanup();
		return -2;
	}
	printf("bind成功!\n");

	//5 监听
	r = listen(serverSocket, 10);
	if (-1 == r) {
		printf("listen失败!\n");
		closesocket(serverSocket);
		WSACleanup();
		return -2;
	}
	printf("listen成功!\n");

	//6 等待客户端连接  阻塞
	SOCKADDR_IN cAddr = { 0 };
	int len = sizeof cAddr;
	SOCKET clientSocket = accept(serverSocket, (sockaddr*)&cAddr, &len);
	if (SOCKET_ERROR == clientSocket) {
		printf("服务器宕机了!\n");
		closesocket(serverSocket);
		// 9 清除协议信息
		WSACleanup();
		return -2;
	}
	printf("有客户端连接到服务器了:%s!\n", inet_ntoa(cAddr.sin_addr));//ip地址从整型转换为字符串的类型

	//7 通信
	char buff[1024];
	while (1) {
		r = recv(clientSocket, buff, 1023, NULL);
		if (r > 0) {
			buff[r] = 0;//添加'\0'
			printf(">>%s\n",buff);
		}
	}
	return 0;
}

多客户端通信

  1. 服务器要接收多个客户端的连接

  2. 多线程来接收多客户端问题

    2.1 有客户端连接到服务器,启动一个线程来和这个客户端通信

    2.2 线程里:

    ​ 2.2.1 接收客户端发来的数据

    ​ 2.2.2 把数据广播给当前连接到服务器的所有客户端

    server.cpp

    #include <stdio.h>
    #include <stdlib.h>
    #include <WinSock2.h>
    
    #pragma comment(lib,"ws2_32.lib")
    #pragma warning(disable:4996)
    SOCKADDR_IN cAddr = { 0 };
    int len = sizeof cAddr;
    SOCKET clientSocket[1024];
    int count = 0;
    
    
    void tongxin(int idx) {
    	char buff[1024];
    	int r;
    	while (1) {
    		r = recv(clientSocket[idx], buff, 1023, NULL);
    		if (r > 0) {
    			buff[r] = 0;
    			printf("%d:%s\n", idx, buff);
    			//广播数据
    			for (int i = 0; i < count; i++) {
    				send(clientSocket[i], buff, strlen(buff), NULL);
    			}
    		}
    	}
    }
    
    int main() {
    	//1 请求协议版本
    	WSADATA wsaData;
    	WSAStartup(MAKEWORD(2, 2), &wsaData);
    	if (LOBYTE(wsaData.wVersion) != 2 ||
    		HIBYTE(wsaData.wVersion) != 2) {
    		printf("请求协议版本失败!\n");
    		return -1;
    	}
    	printf("请求协议成功!\n");
    	//2 创建socket
    	SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    	if (SOCKET_ERROR == serverSocket) {
    		printf("创建socket失败!\n");
    		WSACleanup();
    		return -2;
    	}
    	printf("创建socket成功!\n");
    
    	//3 创建协议地址族
    	SOCKADDR_IN addr = { 0 };
    	addr.sin_family = AF_INET;//协议版本
    	addr.sin_addr.S_un.S_addr = inet_addr("192.168.1.9");//用自己的ip
    	addr.sin_port = htons(10086);//0 - 65535     10000左右
    	//os内核 和其他程序  会占用掉一些端口   80  23  
    
    	//4 绑定
    	int r = bind(serverSocket, (sockaddr*)&addr, sizeof addr);
    	if (-1 == r) {
    		printf("bind失败!\n");
    		closesocket(serverSocket);
    		WSACleanup();
    		return -2;
    	}
    	printf("bind成功!\n");
    
    	//5 监听
    	r = listen(serverSocket, 10);
    	if (-1 == r) {
    		printf("listen失败!\n");
    		closesocket(serverSocket);
    		WSACleanup();
    		return -2;
    	}
    	printf("listen成功!\n");
    
    
    	//6 等待客户端连接    阻塞    尾生抱柱
    	//客户端协议地址族
    	while (1) {
    		clientSocket[count] = accept(serverSocket, (sockaddr*)&cAddr, &len);
    		if (SOCKET_ERROR == clientSocket[count]) {
    			printf("服务器宕机了!\n");
    			//8 关闭socket
    			closesocket(serverSocket);
    			//9 清除协议信息
    			WSACleanup();
    			return -2;
    		}
    		printf("有客户端连接到服务器了:%s!\n", inet_ntoa(cAddr.sin_addr));
    
    		CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)tongxin,
    			(char*)count, NULL, NULL);
    
    		count++;
    	}
    	return 0;
    }
    

    client.cpp

#include <stdio.h>
#include <stdlib.h>
#include <WinSock2.h>
#include <graphics.h>
#pragma comment(lib,"ws2_32.lib")
#pragma warning(disable:4996)


SOCKET clientSocket;
HWND hWnd;
int count = 0;
void jieshou() {
	char recvBuff[1024];
	int r;
	while (1) {
		r = recv(clientSocket, recvBuff, 1023, NULL);
		if (r > 0) {
			recvBuff[r] = 0;
			outtextxy(0, count * 20, recvBuff);
			count++;
		}
	}
}

int main()
{
	hWnd = initgraph(300, 400, SHOWCONSOLE);
	// 1 请求协议版本
	WSADATA wsaData;
	WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) {
		printf("请求协议版本失败!\n");
		return -1;
	}
	//2 创建socket
	clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (SOCKET_ERROR == clientSocket) {
		printf("创建socket失败!\n");
		WSACleanup();
		return -2;
	}

	printf("创建socket成功!\n");

	//3 获取协议地址族
	SOCKADDR_IN addr = { 0 };
	addr.sin_family = AF_INET;//协议版本
	addr.sin_addr.S_un.S_addr = inet_addr("192.168.1.9");
	addr.sin_port = htons(10086); // 0-65535
	// os内核和其他程序会占用一些端口

	//4 连接服务器
	int r = connect(clientSocket, (sockaddr*)&addr, sizeof addr);
	if (-1 == r) {
		printf("连接服务器失败!\n");
		return -1;
	}
	printf("连接服务器成功!\n");

	//5 通信
	char buff[1024];
	CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)jieshou, NULL, NULL, NULL);
	while (1) {
		memset(buff, 0, 1024);
		printf("你想说啥:");
		scanf("%s", buff);
		send(clientSocket, buff, strlen(buff), NULL);
	}
}
    

运行效果:

image-20210311231017381视频教程:
https://www.bilibili.com/video/BV1A4411s7pC?from=search&seid=2542447570726448651

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值