Linxu网络编程——myp2p-qq

功能描述

本博文实现一个类似qq的聊天功能,两个client端连接上服务器,不必知道对方的ip地址,就可以互相发送消息。

预备知识

**1.Linxu网络编程
2.Linux多线程同步技术**

/*
 * pub.h
 *
 *  Created on: 2016年10月30日
 *      Author: Allen
 */

#ifndef PUB_H_
#define PUB_H_
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <pthread.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <signal.h>
#include <sys/types.h>
#define  BUFSIZE 32768

int socket_create(int port);
void socket_accept(int listen_st);
void init_socket_client();
void deliver(int index,const char *buf,int len);
void socket_work(int index);
void *socket_contrl(void *arg);


#endif /* PUB_H_ */
/*
 * pub.c
 *
 *  Created on: 20161030日
 *      Author: Allen
 */

#include"pub.h"

int socket_client[2]; //申明2个socket_client,设为全局变量,管理2个client的socket连接

void init_socket_client() //初始化int socket_client[2]数组
{
    memset(socket_client, 0, sizeof(socket_client));
}

//接收到来自client发送的消息,index0,代表接收到socket_client[0]消息,然后给socket_client[1]发送消息
//index1,代表接收到socket_client[1]消息,然后给socket_client[0]发送消息
//buf为发送消息内容,len为发送消息长度
void deliver(int index, const char *buf, int len)
{
    int rc = 0;
    if (index == 0) //如果 index0,代表01发消息
    {
        if (socket_client[1] == 0) //1不在线
        {
            printf("%d : user not online\n", index);
        } else
        {
            rc = send(socket_client[1], buf, len, 0); //将消息下发给1
            if (rc <= 0)
            {
                if (rc < 0)
                    printf("send faied %s\n", strerror(errno));
                else
                    printf("socket disconnect %s\n", strerror(errno));
            }
        }
    }
    if (index == 1)
    {
        if (socket_client[0] == 0)
        {
            printf("%d : user not online\n", index);
        } else
        {
            rc = 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值