Linux 网络编程四(socket多线程升级版)

//网络编程--客户端
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <pthread.h>
#include <netinet/in.h>
#include <arpa/inet.h>

/*
 强调:当客户端连接服务器时,服务器会产生一个新的文件描述符(套接字)与客户端交互,这个新的套接字不是服务器端的监听套接字
 套接字是全双工的,在一个网络管道中的两端,每端都可以进行读写操作。
 */

typedef struct _recvmodel
{
    int st;
    struct sockaddr_in * addr;
} RecvModel;

//send message
void * send_thread(void *arg)
{
    if (arg == NULL)
    {
        printf("param is not allow NULL!\n");
        return NULL;
    }
    int st = *(int *) arg;
    char buf[1024] = { 0 };
    while (1)
    {
        read(STDIN_FILENO, buf, sizeof(buf));
        if (send(st, buf, strlen(buf), 0) == -1)
        {
            printf("send failed ! error message %s\n", strerror(errno));
            return NULL;
        }
        memset(buf, 0, sizeof(buf));
    }
    return NULL;
}

//recv message
void * recv_thread(void * arg)
{
    if (arg == NULL)
    {
        printf("param is not allow NULL!\n");
        return NULL;
    }
    RecvModel * model = (RecvModel *) arg;
    int flag = 0;
    char buf[1024] = { 0 };
    while (1)
    {
        flag = recv(model->st, buf, sizeof(buf), 0);
        if (flag == 0)
        {
            printf("对方已经关闭连接!\n");
            return NULL;
        } else if (flag == -1)
        {
            printf("recv failed ! error message : %s\n", strerror(errno));
            return NULL;
        }
        printf("from %s:%s", inet_ntoa(model->addr->sin_addr), buf);
        memset(buf, 0, sizeof(buf));
    }
    return NULL;
}

int main(int arg, char *args[])
{
    //打开socket
    int st = socket(AF_INET, SOCK_STREAM, 0);
    if (st == -1)
    {
        printf("open socket failed! error message:%s\n", strerror(errno));
        return -1;
    }
    //定义IP地址结构
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    //设置TCP/IP连接
    addr.sin_family=AF_INET;
    //设置端口号
    addr.sin_port = htons(8080);
    //设置允许连接地址
    addr.sin_addr.s_addr = inet_addr("192.168.1.102");
    //connect server
    int numx = connect(st, (struct sockaddr *) &addr, sizeof(addr));
    if (numx == -1)
    {
        printf("connect server failed ! error message :%s\n", strerror(errno));
        goto END;
    }

    RecvModel model;
    model.st = st;
    model.addr = &addr;
    //开启多线程--线程1接收消息,线程2发送消息
    pthread_t thr1, thr2;
    if (pthread_create(&thr1, NULL, send_thread, &st) != 0)
    {
        printf("create thread failed ! \n");
        goto END;
    }
    if (pthread_create(&thr2, NULL, recv_thread, &model) != 0)
    {
        printf("create thread failed ! \n");
        goto END;
    }
    pthread_join(thr1, NULL);
    pthread_join(thr2, NULL);
    END: close(st);
    return 0;
}
//网络编程--服务端
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <pthread.h>
#include <netinet/in.h>
#include <arpa/inet.h>

typedef struct _recvmodel
{
    int st;
    struct sockaddr_in * addr;
} RecvModel;

//send message
void * send_thread(void *arg)
{
    if (arg == NULL)
    {
        printf("param is not allow NULL!\n");
        return NULL;
    }
    int st = *(int *) arg;
    char buf[1024] = { 0 };
    while (1)
    {
        read(STDIN_FILENO, buf, sizeof(buf));
        if (send(st, buf, strlen(buf), 0) == -1)
        {
            printf("send failed ! error message %s\n", strerror(errno));
            return NULL;
        }
        memset(buf, 0, sizeof(buf));
    }
    return NULL;
}

//recv message
void * recv_thread(void * arg)
{
    if (arg == NULL)
    {
        printf("param is not allow NULL!\n");
        return NULL;
    }
    RecvModel * model = (RecvModel *) arg;
    int flag = 0;
    char buf[1024] = { 0 };
    while (1)
    {
        flag = recv(model->st, buf, sizeof(buf), 0);
        if (flag == 0)
        {
            printf("对方已经关闭连接!\n");
            return NULL;
        } else if (flag == -1)
        {
            printf("recv failed ! error message : %s\n", strerror(errno));
            return NULL;
        }
        printf("from %s:%s", inet_ntoa(model->addr->sin_addr), buf);
        memset(buf, 0, sizeof(buf));
    }
    return NULL;
}

int main(int arg, char *args[])
{

    //short port = atoi(args[1]);
    //打开socket
    int st = socket(AF_INET, SOCK_STREAM, 0);
    if (st == -1)
    {
        printf("open socket failed! error message:%s\n", strerror(errno));
        return -1;
    }
    //设置系统地址可重用
    int on = 1;
    if (setsockopt(st, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1)
    {
        printf("setsockpot failed ! error message %s\n", strerror(errno));
        goto END;
    }
    //定义IP地址结构
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    //设置TCP/IP连接
    addr.sin_family = AF_INET;
    //设置端口号
    addr.sin_port = htons(8080);
    //设置允许连接地址
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    //bind ip
    if (bind(st, (struct sockaddr *) &addr, sizeof(addr)) == -1)
    {
        printf("bind ip failed ! error message :%s\n", strerror(errno));
        goto END;
    }
    //监听连接
    if (listen(st, 20) == -1)
    {
        printf("listen failed ! error message :%s\n", strerror(errno));
        goto END;
    }
    //接收客户端连接(阻塞)
    struct sockaddr_in client_addr;
    memset(&client_addr, 0, sizeof(client_addr));
    socklen_t client_addrlen = sizeof(client_addr);
//强调:这里的client_addrlen并不是为了在函数中设置client_addrlen的值,而是通过client_addrlen的值来判断client_addr是一个什么类型的结构,
//所以这里client_addrlen设置为0是错误的,必须是struct sockaddr_in这个结构的大小,不然返回值不正确
int client_st = accept(st, (struct sockaddr *) &client_addr, &client_addrlen); if (client_st == -1) { printf("accept failed ! error message :%s\n", strerror(errno)); goto END; } RecvModel model; model.st = client_st; model.addr = &client_addr; printf("accept by=%s\n",inet_ntoa(client_addr.sin_addr)); //开启多线程--线程1接收消息,线程2发送消息 pthread_t thr1, thr2; if (pthread_create(&thr1, NULL, send_thread, &client_st) != 0) { printf("create thread failed ! \n"); goto END; } if (pthread_create(&thr2, NULL, recv_thread, &model) != 0) { printf("create thread failed ! \n"); goto END; } pthread_join(thr1, NULL); pthread_join(thr2, NULL); //关闭客户端管道 close(client_st); END: close(st); return 0; }
.SUFFIXES:.c .o
CC=gcc
SRCS1=mserver.c
SRCS2=mclient.c
OBJS1=$(SRCS1:.c=.o)
OBJS2=$(SRCS2:.c=.o)
EXEC1=mserv
EXEC2=mcli

start:$(OBJS1) $(OBJS2)
    $(CC) -o $(EXEC1) $(OBJS1) -lpthread
    $(CC) -o $(EXEC2) $(OBJS2) -lpthread
    @echo "^_^ ------ OK ------ ^_^"
.c.o:
    $(CC) -Wall -g -o $@ -c $<
clean:
    rm -f $(OBJS1)
    rm -f $(OBJS2)
    rm -f $(EXEC1)
    rm -f $(EXEC2)
小结:这段升级版程序花费3小时,出现一个错误提示:" Transport endpoint is not connected",我仔细查找资料,
网上说是socket套接字不对,可我程序中套接字是正确的,
我没有办法,但是我有一个成功的程序,就是第一版socket程序,我将原来的socket程序复制到我的新程序中,一句句替换,终于发现这个问题
问题:我缺少addr.sin_family = AF_INET;//将网络地址类型设置为TCP/IP协议;这句代码。缺少这段代码是导致报错的主要原因。
另外注意我代码中强调的内容--网络管道是全双工的

 

posted on 2016-09-16 23:27  寒魔影  阅读(3766)  评论(0编辑  收藏  举报

导航