c++ socket 网络编程

客户端

  • 实例化一个sockaddr_in,里面有协议簇(ipv4或者ipv6)、服务器ip、服务器port;
  • 实例化一个socket,参数有ipv4/ipv6,tcp/udp;记得判断是否成功;
  • 对实例化的socket设置选项,比如读写buffer大小,是否阻塞模式;
  • connect,参数就是上面的sockaddr_in和socket;记得判断是否成功;
void function(){
    uint32_t ip;
    uint16_t port;
	struct sockaddr_in addr;
	memset(&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;//ipv4
	addr.sin_addr.s_addr = htonl(ip);
	addr.sin_port = htons(port);
	//ipv4,tcp
	int sock = socket(AF_INET, SOCK_STREAM, 0);
	if (sock < 0) {
	//实例化失败
	}
	//设置成非阻塞
	set_nonblock(sock, TRUE);
    //设置读写buffer
	int sock_rcv_buf_sz = 512 * 1024;
	if (-1 == (ret = setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
		(void*)&sock_rcv_buf_sz, sizeof(sock_rcv_buf_sz))))
	{
	    //设置读buffer失败
		close(sock);
		sock = -1;
	}

	if (-1 == (ret = setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
		(void*)&sock_rcv_buf_sz, sizeof(sock_rcv_buf_sz))))
	{
	    //设置写buffer失败
	    close(sock);
		sock = -1;
	}
	int r = connect(sock, (struct sockaddr*) &addr, sizeof(addr));
	if (r < 0) {
		if ((errno != EINPROGRESS) && (errno != EINTR)) {
		}
		//失败
	}
	else if (r == 0) {
	//成功
	}
}

int set_nonblock(int fd, boolean on)
{
	int flags = 1;
	if (fd > 0) {
		flags = fcntl(fd, F_GETFL);
		if (-1 == flags)
			return -1;
		if (on)
			flags |= O_NONBLOCK;
		else
			flags &= ~O_NONBLOCK;
		if (0 != fcntl(fd, F_SETFL, flags))
			return -2;
	}
	return 0;
}

你可能感兴趣的:(c++ socket 网络编程)