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

📄 socketconnection.cpp

📁 linux下的异步通信库 支持TCP和UDP异步通信 编译和使用前先读readme.
💻 CPP
字号:
/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Library General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

// SocketConnection.cpp - Copyright (C) 2002, Simon Brenner

#include <fcntl.h>
#include <unistd.h>

#include <errno.h>

#include "async.h"
#include "SocketConnection.hpp"

SocketConnection::SocketConnection(): 
	default_srv(NULL),
	default_srvport(0)
{}

SocketConnection::SocketConnection(char *srvaddr, int srvport):
	default_srv(srvaddr),
	default_srvport(srvport)
{}

SocketConnection::SocketConnection(int fd):
	FdConnection(fd),
	default_srv(NULL),
	default_srvport(0)
{}

SocketConnection::~SocketConnection()
{
	if (fd != -1)
	{
		if (LastSocketObject(fd))
			close(fd);
		RemoveSocket(fd, this);
	}
}

int SocketConnection::MakeSocket(int socktype) return ret
{
	ret=socket(PF_INET, socktype, 0);
	if (ret<0)
	{
		return false;
	}
/*	if (conn)
	{
		if (connect(ret, name, namelen)<0)
		{
			return false;
		}
	}
	else
	{
		if (bind(ret, name, namelen)<0)
		{
			return false;
		}
	}*/
	return ret;
}

int SocketConnection::Bind(int port, int socktype)
{
	sockaddr_in name;
	name.sin_family=AF_INET;
	name.sin_port=htons(port);
	name.sin_addr.s_addr=htonl(INADDR_ANY);
	Disconnect();
	fd=MakeSocket(socktype);
	if (fd<0)
		return fd;
	else
	{
		if (bind(fd, (sockaddr *)&name, sizeof(name))<0)
			Disconnect();
		AddSocket(fd, this);
		return fd;
	}
};

void SocketConnection::Disconnect()
{
	printf("SocketConnection::Disconnect()\n");
	if (fd != -1)
	{
		printf("SocketConnection::Disconnect(): has socket (fd: %d), closing it\n", fd);
		close(fd);
		if (LastSocketObject(fd))
			RemoveSocket(fd, this);
	}
	fd=-1;
}

⌨️ 快捷键说明

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