winsock编程

2020/10/25 11:14
阅读数 21

基于TCP的通信程序

server

#include<stdio.h>
#include <winsock2.h>
#include <windows.h>
#pragma comment(lib,"WS2_32.lib")			
 
int main()									
{
   
   
	//初始化WSA
	WORD sockVersion = MAKEWORD(2, 2);
	WSADATA wsaData;
	if (WSAStartup(sockVersion, &wsaData) != 0){
   
   
		return 0;
	}
 
	//创建套接字
	SOCKET slisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (slisten == INVALID_SOCKET){
   
   
		printf("socket error !");
		return 0;
	}
 
	//绑定IP和端口  bind
	struct sockaddr_in sin;
	sin.sin_family = AF_INET;
	sin.sin_port = htons(6802);
	sin.sin_addr.S_un.S_addr = INADDR_ANY;
	if (bind(slisten, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR){
   
   
		printf("bind error !");
	}

	//listen
	if (listen(slisten, 5) == SOCKET_ERROR){
   
   
		printf("listen error !");
		return 0;
	}

	//accept
	SOCKET sClient;
	struct sockaddr_in remoteAddr;
	int nAddrlen = sizeof(remoteAddr);
	printf("等待连接...\n");
	sClient = accept(slisten, (SOCKADDR *)&remoteAddr, &nAddrlen);

	printf("接受到一个连接:%s \r\n", inet_ntoa(remoteAddr.sin_addr));
 
	//接收数据
	char revData[255];
	int ret = recv(sClient, revData, 255, 0);
	//printf(ret);
	if (ret > 0){
   
   
		revData[ret] = 0x00;
		printf(revData);
	}


	return 0;
}

client

#include <stdio.h>
#include <winsock2.h>
#include <windows.h>
#pragma comment(lib,"WS2_32.lib")		
 
int main()							
{
   
   
	WORD sockVersion = MAKEWORD(2, 2);
	WSADATA data;
	if (WSAStartup(sockVersion, &data) != 0){
   
   
		return 0;
	}
 
	SOCKET sclient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (sclient == INVALID_SOCKET){
   
   
		printf("invalid socket !");
		return 0;
	}
 
	//connect
	struct sockaddr_in serAddr;
	serAddr.sin_family = AF_INET;
	serAddr.sin_port = htons(6802);
	serAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
	if (connect(sclient, (struct sockaddr *)&serAddr, sizeof(serAddr)) == SOCKET_ERROR){
   
   
		printf("connect error !");
		closesocket(sclient);
		return 0;
	}

	//发送数据
	char * sendData = "你好,TCP客户端!\n";
	send(sclient, sendData, strlen(sendData), 0);

	return 0;
}

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部