Tcp Socket编程实例

基本通信:

服务端:

#include<WINSOCK2.H>
#include<iostream>
using namespace std;

const int port = 9900;
const int BUF_SIZE = 1024;

int main()
{
	WSADATA wsaData;
	WORD wVersionRequired;
	wVersionRequired = MAKEWORD(2,0);
   
	if (WSAStartup(wVersionRequired,&wsaData) != 0)
	{
		cout<<"初始化失败。"<<endl;
		return -1;

	}

	//初始化socket
	SOCKET sock;
	sock = socket(AF_INET,SOCK_STREAM,0);
		if (INVALID_SOCKET == sock)
		{
			cout<<"创建失败"<<endl;
			WSACleanup();
			return -1;
		}
	//绑定套接字
		sockaddr_in myaddr;
		myaddr.sin_family = AF_INET;
		myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
		myaddr.sin_port = htons(port);

		if(bind(sock,(SOCKADDR*)&myaddr,sizeof(myaddr)) == SOCKET_ERROR)
		{
			cout<<"绑定失败!"<<endl;
			return -1;
		}

		//listen另一端的socket
		if (listen(sock,5) == SOCKET_ERROR)
		{
			cout<<"监听失败。"<<endl;
		}
		else
		{
			cout<<"开始监听:"<<endl;
		
		}
		
		//对方连接
	

		
		SOCKET CliSock;
	
		CliSock = accept(sock,NULL,NULL);
		
		if (CliSock == INVALID_SOCKET)
		{
			cout<<"客户端出错。"<<endl;
			return -1;
		}
		else
		{
			cout<<"接收客户端数据:"<<endl;
			char buf[BUF_SIZE];
			memset(buf,0,BUF_SIZE);
			int len = recv(CliSock,buf,BUF_SIZE,MSG_PEEK);
			if (len>0)
			{
				cout<<"数据为:"<<buf<<endl;
			}
		}

		
		if (!closesocket(sock))
		{
			WSAGetLastError();
			return -1;
		}
		if (!closesocket(CliSock))
		{
			WSAGetLastError();
				return -1;
		}
		if (!WSACleanup())
		{
			WSAGetLastError();
			return -1;
		}

	
		return 0;
}


客户端:

#include<iostream>
#include<WINSOCK2.H>
using namespace std;

const int port = 9900;
const int BUF_SIZE = 1024;

int main()
{
	WSADATA wsaData;
	WORD wVersionRequired;
	wVersionRequired = MAKEWORD(2,0);

	if (WSAStartup(wVersionRequired,&wsaData) != 0)
	{
		cout<<"初始化失败。"<<endl;
		return -1;
	}

	//创建套接字
	SOCKET sock;
	sock = socket(AF_INET,SOCK_STREAM,0);

	if (sock == INVALID_SOCKET)
	{
		cout<<"初始化socket失败。"<<endl;
		return -1;
	}

	//设置服务端的端口和地址
	sockaddr_in serAddr;
	serAddr.sin_family = AF_INET;
	serAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
	serAddr.sin_port = htons(port);

	if (connect(sock,(SOCKADDR*)&serAddr,sizeof(serAddr)) == SOCKET_ERROR)
	{
		cout<<"连接错误!"<<endl;
	}
	else
	{
		cout<<"连接成功"<<endl;
		char buf[BUF_SIZE];
		cin>>buf;
		send(sock,buf,sizeof(buf),0);
		closesocket(sock);
		WSACleanup();

	}

}


 

你可能感兴趣的:(Tcp Socket编程实例)