sock_ev——linux平台socket事件框架(基于数据报的测试程序)

上一篇已经做过注释,这一篇直接上代码

/***************************************************************************************
****************************************************************************************
* FILE		: server_test.cc
* Description	: 
*			  
* Copyright (c) 2012 by Liu Yanyun(E-mail:liuyun827@foxmail.com). All Rights Reserved.
*            Without permission, shall not be used for any commercial purpose
* 
* History:
* Version		Name       		Date			Description
   0.1		Liu Yanyun		2012/12/03		Initial Version
   
****************************************************************************************
****************************************************************************************/


#include "socket.h"
#include "log_trace.h"
#include "socket_addr.h"
#include "socket_base.h"
#include "event_loop.h"
#include <iostream>

using namespace std;

int main()
{ 
  Socket *ser = Socket::create();
  bool ret = ser->open("dgram://unix.domain.ipc.1");

  char buf[100] = {0};
  char addr[128] = {0};

  ser->recv(buf, sizeof(buf), addr);

  printf("from:%s;buf:%s\n", addr, buf);
  
  ser->send(buf, strlen(buf), addr);

  Socket::destroy(ser);
  
  return 0;
}


/***************************************************************************************
****************************************************************************************
* FILE		: client_test.cc
* Description	: 
*			  
* Copyright (c) 2012 by Liu Yanyun(E-mail:liuyun827@foxmail.com). All Rights Reserved.
*            Without permission, shall not be used for any commercial purpose
* 
* History:
* Version		Name       		Date			Description
   0.1		Liu Yanyun		2012/12/03		Initial Version
   
****************************************************************************************
****************************************************************************************/


#include "socket.h"
#include "log_trace.h"
#include "socket_addr.h"
#include "socket_base.h"
#include <iostream>

using namespace std;

int main()
{
  Socket *clt = Socket::create();
  bool ret = clt->open("dgram://unix.domain.ipc.2");
  ret = ret;

  char buf[100] = {"hello"};
  char addr[128] = {0};

  clt->send(buf, strlen(buf), "dgram://unix.domain.ipc.1");

  clt->recv(buf, sizeof(buf), addr);

  printf("from:%s;buf:%s\n", addr, buf);

  sleep(2);
  
  Socket::destroy(clt);
  
  return 0;
}
起两个shell结果为:
./server_test
from:dgram://unix.domain.ipc.2;buf:hello

./client_test
from:dgram://unix.domain.ipc.1;buf:hello


上面是使用unix域套接字进程测试;修改地址为ip:port形式可以转为inet域。

对于数据包式的通信,只需要各自打开自身的地址,然后就可以根据地址收发数据了;而在上一篇中对于字节流方式服务器端要先打开进行监听,然后客户端去连接,服务器端接受连接以后才可以进行通信。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值