⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 network.cpp

📁 Visual C++ 游戏开发与设计实例 源代码(所有)
💻 CPP
字号:

#include "global.h"
#include "msglist.h"
#include "network.h"

#include <winsock2.h>

//-----------------------------------------------------------------------------
// Connection parameters
//-----------------------------------------------------------------------------
#define NET_SERVER_ADDR			"127.0.0.1"
#define NET_SERVER_PORT			5500
#define NET_CLIENT_PORT_MIN		5400
#define NET_CLIENT_PORT_MAX		5420
#define BUFFERSIZE				256

//-----------------------------------------------------------------------------
// Variables
//-----------------------------------------------------------------------------
CMsgList			NetList;

SOCKET				c_socket;			// client socket
unsigned int		c_port;				// client port

bool SendMsg(int msg, LPVOID param, int size);
DWORD WINAPI MsgReceiver( LPVOID param );
//-----------------------------------------------------------------------------
// Name: InitNetwork()
// Desc: Initialize socket for network and connect to the server
//-----------------------------------------------------------------------------
bool InitNetwork( const char *serv_addr, unsigned int serv_port)
{
	WSADATA			wsd;
	sockaddr_in		local,server;
	unsigned long	ul = 1;
	int				ret;

	// Load network library
	if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0)
		return false;

	// Create a client socket and bind it
	c_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
    if (c_socket == SOCKET_ERROR)
    		return false;

	local.sin_addr.s_addr = htonl(INADDR_ANY);
	local.sin_family = AF_INET;

	c_port = NET_CLIENT_PORT_MIN;
	while(c_port < NET_CLIENT_PORT_MAX)
	{
		local.sin_port = htons(c_port);
		if(bind(c_socket,(struct sockaddr *)&local,
			sizeof(local)) == SOCKET_ERROR)	{
			ret = WSAGetLastError();
			if(ret == WSAEADDRINUSE)
				c_port++;
			else break;
		}
		else break;
	}
	if(c_port >= NET_CLIENT_PORT_MAX)
		return false;
	
	// Connect to the server
	server.sin_addr.s_addr 	= inet_addr(serv_addr);
	server.sin_family	= AF_INET;
	server.sin_port		= htons(serv_port);

	if( connect( c_socket, (const sockaddr *)&server,
		sizeof(server) ) == SOCKET_ERROR )
	{
		ret = WSAGetLastError();
		if(ret == WSAENETDOWN || ret == WSAENETUNREACH)
			ERRORMSG("Can't reach server.\nPlease check your network connection.");
		else if(ret == WSAECONNREFUSED)
			ERRORMSG("The server does not work!");
		else if(ret == WSAEPROCLIM)
			ERRORMSG("Too many users.\nPlease try later.");
		return false;
	}

	// Set nonblock property
	if( ioctlsocket( c_socket, FIONBIO, &ul ) == SOCKET_ERROR )
		return false;

	// Initialize message lists
	NetList.CreatMsgList( 8, true );		// network message list

	// Create receive thread
	HANDLE hThread = CreateThread(NULL,0,MsgReceiver,NULL,0,NULL);
	if(!hThread)
		return false;

	return true;
}



//-----------------------------------------------------------------------------
// Name: SendMsg()
// Desc: Function for sending messages to the server
//-----------------------------------------------------------------------------
bool SendMsg(int msg, LPVOID param, int size)
{
	int		ret = size+sizeof(int)*2;
	char	*buffer = new char[ret];
	
	if(!buffer)
		return false;

	*(int *)buffer = msg;
	*(int *)(buffer+sizeof(int)) = size;
	if(param && size>0)
		memcpy( buffer+sizeof(int)*2, param, size );
	ret = send(c_socket,buffer,ret,0);
	delete[] buffer;

	if( ret == SOCKET_ERROR)
		return false;
	else
		return true;
}



//-----------------------------------------------------------------------------
// Name: MsgReceiver()
// Desc: Initialize socket for network and connect to the server
//-----------------------------------------------------------------------------
DWORD WINAPI MsgReceiver( LPVOID param )
{
	fd_set			fdread;
	timeval			tval;
	int				ret, msgsize;
	char			buf_char[BUFFERSIZE];		// receive buffer
	char			*mark;
	CMsgElem		elem;

	// initiate communication
	ret = 0;
	SendMsg( NETMSGTK_ASKGROUPINFO, &ret, sizeof(int) );

	tval.tv_usec = 0;
	tval.tv_sec	 = 1;
	while(true)
	{
		FD_ZERO(&fdread);
		FD_SET(c_socket,&fdread);
		ret = select(0,&fdread,NULL,NULL,&tval);
		if ( ret == 0 || ret == SOCKET_ERROR ) {
			ret = WSAGetLastError();
			continue;
		}

		if ( !NetList.GetSize() )		// may be not initialized yet
			continue;

		ret = recv(c_socket,buf_char,BUFFERSIZE,0);
		if(ret == SOCKET_ERROR) {
			ret = WSAGetLastError();
			NetList.Lock();
			char	*temp = "Connection shutdown!";
			elem.CreateMsgElem(MSGNET_RECEIVEERROR, temp, strlen(temp)+1, MSG_NET );
			NetList.Push(&elem);
			NetList.UnLock();
			break;
		}

		// Peek message details and push into the list
		NetList.Lock();
		mark = buf_char;
		while ( ret > 0 && 
			elem.CreateMsgElemFromBuf( mark, msgsize, MSG_NET ) ) {
			NetList.Push(&elem);
			mark += msgsize;
			ret -= msgsize;
		}
		NetList.UnLock();
	}
	return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -