您的位置:首页 > 运维架构 > Linux

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

2012-12-04 19:41 423 查看
上一篇已经做过注释,这一篇直接上代码

/***************************************************************************************
****************************************************************************************
* 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域。

对于数据包式的通信,只需要各自打开自身的地址,然后就可以根据地址收发数据了;而在上一篇中对于字节流方式服务器端要先打开进行监听,然后客户端去连接,服务器端接受连接以后才可以进行通信。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: