【WinSocket】WinSocket 之TCP示例

一,TCP通信过程

服务端:

       socket( ) //定义socket

       bind( ) //绑定本地地址和端口号

       listen( ) //监听客户端请求

       accept( ) //接收客户端请求

       recv( ) //接收客户端数据

       closesocket( )

客户端:

       socket( )

       connect( )  //请求连接服务器

       send( )      //发送消息

       closesocket( )

【WinSocket】WinSocket 之TCP示例_第1张图片

 

 

1)服务端:       

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

#define BUFLEN 1024

int main()
{
	SOCKET serversoc;
	SOCKET clientsoc;
	SOCKADDR_IN serveraddr;
	SOCKADDR_IN clientaddr;
	char buf[BUFLEN];
	int len;

         WSADATA wsa;
	WSAStartup(MAKEWORD(1,1),&wsa);	//initial Ws2_32.dll by a process
	if((serversoc = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) <= 0)	//create a tcp socket
	{
		printf("Create socket fail!\n");
		return -1;
	}
	
	serveraddr.sin_family = AF_INET;
	serveraddr.sin_port = htons(9102);
	serveraddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);

	if(bind(serversoc, (SOCKADDR *)&serveraddr, sizeof(serveraddr)) != 0)
	{
		printf("Bind fail!\n");
		return -1;
	}
	
	//start listen, maximum length of the queue of pending connections is 1
	printf("Start listen...\n");
	if(listen(serversoc, 1) != 0)      //监听客户端的请求
	{
		printf("Listen fail!\n");
		return -1;
	}

	len = sizeof(SOCKADDR_IN);
	
	if((clientsoc = accept(serversoc, (SOCKADDR *)&clientaddr, &len))<=0)//接收客户端的请求
	{
		printf("Accept fail!\n");
		return -1;
	}
	printf("Connected\n");
	while(1)//打印客户端发送的消息
	{
		if(recv(clientsoc, buf, BUFLEN, 0) <= 0)	
		{
			//some error occur
			printf("Close connection\n");
			closesocket(clientsoc);
			break;
		}
		else
		{
			printf("%s\n",buf);
		}
		
	}
	
	WSACleanup(); //clean up Ws2_32.dll 
	return 0;
}


2)客户端

#include <stdio.h>
#include <winsock2.h>

#pragma comment(lib,"ws2_32.lib")
#define BUFLEN 1024
int main()
{
	SOCKET soc;
	SOCKADDR_IN serveraddr;  //TCP使用的都是socket_in数据结构
	SOCKADDR_IN clientaddr;
	char buf[BUFLEN];

         WSADATA wsa;
	WSAStartup(MAKEWORD(1,1),&wsa);	//initial Ws2_32.dll by a process

	if((soc = socket(AF_INET,       //TCP/IP协议
		             SOCK_STREAM,   //TCP流传输
					 IPPROTO_TCP)) <= 0)	//create a tcp socket
	{
		printf("Create socket fail!\n");
		return -1;
	}

	serveraddr.sin_family = AF_INET;
	serveraddr.sin_port = htons(9102);  //服务端服务的端口号
	serveraddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");//服务器的IP地址

	//connect to server
	printf("Try to connect...\n");
	if(connect(soc, (SOCKADDR *)&serveraddr, sizeof(serveraddr)) != 0)//请求连接服务器
	{
		printf("Connect fail!\n");
		return -1;
	}
	printf("Connected\n");
	while(1)//不断的向服务器发送消息
	{
		scanf("%s", buf);
		if(send(soc, buf, strlen(buf)+1, 0)<=0)
		{
			printf("Error!\n");
		}
	}

	WSACleanup(); //clean up Ws2_32.dll 
	return 0;
}


 

你可能感兴趣的:(【WinSocket】WinSocket 之TCP示例)