linux c语言socket编程实例(1server-1client),一个服务器,一个客户端

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_39465823/article/details/81219393

服务器端代码:

/**************************************************
##filename      : server.c
##author        : GYZ                              
##e-mail        : 1746902011@qq.com                
##create time   : 2018-07-23 10:41:42
##last modified : 2018-07-24 14:05:28
##description   : NA                               
**************************************************/

#include <stdio.h>                                
#include <stdlib.h>                                
#include <string.h>                                
#include <sys/socket.h>                                                   
#include <sys/types.h>
#include <unistd.h> 
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <errno.h>

int main(int argc,char *argv[])                    
{                                                  
    int server_sockfd;
    int client_sockfd;
    int ret;
    struct sockaddr_in server_addr;
    struct sockaddr_in client_addr;
    socklen_t server_addrlen;
    socklen_t client_addrlen;
    char data[100];
    char data1[100];
    int on = 1;

    /*1,create a socket*/
    /*IPPROTO=0,dumserver protocol for TCP*/
    server_sockfd = socket(AF_INET,SOCK_STREAM,0);
    if(-1 == server_sockfd)
    {
        perror("socket"),exit(-1);
    }
    /*1.5 enable address reuse*/
    ret = setsockopt(server_sockfd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));
    /*2,bind the socket with an ip*/
    memset(&server_addr,0,sizeof(struct sockaddr_in));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(666);
    server_addr.sin_addr.s_addr = inet_addr("121.121.121.121");
    server_addrlen = sizeof(struct sockaddr);
    ret = bind(server_sockfd,(const struct sockaddr*)&server_addr,server_addrlen);
    if(-1 == ret)
    {
        perror("bind"),exit(-1);
    }
    /*3,listen the socket*/
    ret = listen(server_sockfd,6);
    if(-1 == ret)
    {
        perror("listen"),exit(-1);
    }
    while(1)
    {
        /*4,accept the data from the client*/
        client_addrlen = sizeof(struct sockaddr);
        client_sockfd = accept(server_sockfd,(struct sockaddr *)&client_addr,&client_addrlen);
        if(-1 == client_sockfd)
        {
            perror("accept"),exit(-1);
        }
        printf("IP is %s\n",inet_ntoa(client_addr.sin_addr));
        printf("Port is %d\n",ntohs(client_addr.sin_port));
        while(1)
        {
            /*5,read the data from client*/
            ret = recv(client_sockfd,data,100,0);
            if(-1 == ret)
            {
                perror("recv"),exit(-1);
            }
            printf("data from client:%s\n",data);
            /*6,send the data to client*/
            printf("server send data:");
            scanf("%s",data1);
            ret = send(client_sockfd,data1,100,0);
            if(-1 == ret)
            {
                perror("send"),exit(-1);
            }
        }
    }
    close(client_sockfd);
    close(server_sockfd);
    return 0;                                      
}                                                  
                                                   

客户端代码:

    #include <stdio.h>                                
#include <stdlib.h>                                
#include <string.h>                                
#include <sys/socket.h>                                                   
#include <sys/types.h>
#include <unistd.h> 
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <errno.h>

                 

/**************************************************
##filename      : client.c
##author        : GYZ                              
##e-mail        : 1746902011@qq.com                
##create time   : 2018-07-23 16:36:34
##last modified : 2018-07-24 14:09:39
##description   : NA                               
**************************************************/
#include "cs_socket.h"

int main(int argc,char *argv[])                    
{                                                  
    int client_sockfd;
    struct sockaddr_in client_addr;
    socklen_t client_addrlen;
    char data[20];
    char data1[20];
    int ret;

    /*1,create a socket*/
    client_sockfd = socket(AF_INET,SOCK_STREAM,0);
    if(-1 == client_sockfd)
    {
        perror("socket"),exit(-1);
    }
    /*2,connect to the server*/
    memset(&client_addr,0,sizeof(struct sockaddr));
    client_addr.sin_family = AF_INET;
    client_addr.sin_port = htons(666);
    client_addr.sin_addr.s_addr = inet_addr("121.121.121.121");
    client_addrlen = sizeof(struct sockaddr);
    ret = connect(client_sockfd,(const struct sockaddr *)&client_addr,client_addrlen);
    if(-1 == ret)
    {
        perror("connect"),exit(-1);
    }
    while(1)
    {
        /*3,send the data to server*/
        printf("client data are :");
        scanf("%s",data);
        ret = send(client_sockfd,data,20,0);
        if(-1 == ret)
        {
            perror("write"),exit(-1);
        }
        /*4,receive the data from server*/
        ret = recv(client_sockfd,data1,100,0);
        if(-1 == ret)
        {
            perror("recv"),exit(-1);
        }
        printf("data from server:%s\n",data1);
    }
    close(client_sockfd);
    return 0;                                      
}                                                  
                                                   
   makefile文件:

all:server client

CC = gcc
SRC1 = server.c
SRC2 = client.c
OBJE1 = server
OBJE2 = client

${OBJE1}: 
    ${CC} ${SRC1} -o ${OBJE1} 
${OBJE2}:
    ${CC} ${SRC2} -o ${OBJE2} 

.PHONY:clean
clean :
    rm ${OBJE1} ${OBJE2}
 

                                               

                 

展开阅读全文

c语言 socket 网络编程 一个客户端,多个服务器问题

08-11

服务器代码:rn#include rn#include rn#include rn#include rn#pragma comment(lib, "wsock32.lib")rnrnSOCKET sck,consck[10];rnint cur = 0;rnstruct sockaddr_in temp[10];rnrnvoid listen_proc(void * pdummy)rnrn int index = cur;rn cur++;rn char buf[256]; int r = 0;rn for(;;) rn rn memset(buf, 0, 256);rn r = recv(consck[index], buf, 256, 0);rn if (r < 1) break;rn printf("收到%s的数据:%s\n", inet_ntoa(temp[index].sin_addr ), buf);rn rn return;rnrnrnvoid accept_proc(void * pdummy)rn rn for(int i = 0;1;i++) rn rn int length = sizeof(temp[i]);rn consck[i] = accept(sck, (struct sockaddr *)&temp[i], &length);rn printf("%s接收成功...\n", inet_ntoa(temp[i].sin_addr ));rn _beginthread(&listen_proc, 0, 0);rn rn return;rnrnrnrnvoid main()rn rn /*Socket()*/rn WSAData w; rn memset(&w, 0, sizeof(w));rn if(WSAStartup(0x0101, &w)) //启动Socketrn rn printf("启动Socket失败!");rn exit(0);rn rn printf("启动Socket成功...\n");rnrn sck = socket(AF_INET, SOCK_STREAM, 0); //创建Socketrn printf("创建Socket成功...\n");rnrn /*Bind(),绑定ip地址和端口号*/rn struct sockaddr_in my_addr;rnrn memset(&my_addr, 0, sizeof(my_addr));rn my_addr.sin_family = AF_INET; //设置版本rn my_addr.sin_port = htons(10000); //设置端口号rn my_addr.sin_addr.S_un.S_addr = INADDR_ANY; //设置服务器IP地址rn //my_addr.sin_addr.S_un.S_addr = inet_addr(ip); //设置服务器IP地址rnrn if(bind(sck, (sockaddr *)&my_addr, sizeof(my_addr)) == SOCKET_ERROR) rn rn printf("绑定Scoket失败!\n"); rn exit(0);rn rn printf("绑定Socket成功...\n"); rn rnrn /*Listen()*/rn listen(sck, 5);rn printf("服务器监听状态...\n");rnrnrn /*Accept()*/rn _beginthread(&accept_proc, 0, 0);rnrn rn rn rn /*Send()*/rn char buf[256];rn int s;rn do rn rn memset(buf, 0, 256);rn gets(buf);rn s = send (consck[0], (char *)&buf, sizeof(buf),0);rn if ( s < 1) break;rn rn while(!strstr(buf, "exit"));rnrn WSACleanup();rnrnrnrn客户端代码:rn#include rn#include rn#include rn#include rn#pragma comment(lib, "wsock32.lib")rnrnSOCKET sck;rnrnrnvoid listen_proc(void * pdummy)rnrn char buf[256]; int r = 0;rn for(;;) rn rn memset(buf, 0, 256);rn r = recv(sck , buf, 256, 0);rn if (r < 1) break;rn printf("收到数据:%s\n", buf);rn rn return;rnrnrnrnvoid main()rnrn /*Socket()*/ rn WSAData w; memset(&w, 0, sizeof(w));rn if(WSAStartup(0x0101, &w)) //启动Socketrn rn printf("启动Socket失败!");rn exit(0);rn rn printf("启动Socket成功...\n");rnrn sck = socket(AF_INET, SOCK_STREAM, 0); //创建Socketrn printf("创建Socket成功...\n");rn rn /*Connet()*/rn hostent *phost=gethostbyname("我的域名");rn in_addr addr;rn char* ip;rn for(int i=0;;i++)rn rn char *p=phost->h_addr_list[i];rn if(p==NULL)rn break;rn memcpy(&addr.S_un.S_addr,p,phost->h_length);rn ip = inet_ntoa(addr);rn rnrn struct sockaddr_in client; rn client.sin_family = AF_INET; //设置版本rn client.sin_port = htons(10000); //设置端口号rn client.sin_addr.S_un.S_addr = inet_addr(ip); //设置IP地址rn //client.sin_addr.S_un.S_addr = inet_addr("192.168.1.22"); //设置IP地址rn if(connect(sck, (struct sockaddr *)&client, sizeof(sockaddr)))rn rn printf("服务器连接失败!\n");rn exit(0);rn rn printf("服务器连接成功...\n"); rnrn /*Recv()*/rn printf("开始接收信息...\n");rn _beginthread(&listen_proc, 0, 0);rn rn rn /*Send()*/rn char buf[256];rn int s;rn do rn rn memset(buf, 0, 256);rn gets(buf);rn s = send (sck, (char *)&buf, sizeof(buf),0);rn if ( s < 1) break;rn rn while(!strstr(buf, "exit"));rnrn WSACleanup();rnrnrnrn为什么打开服务器之后,第一个客户端能够正常连接,第二个客户端无法连接成功? 论坛

linux c 多进程的服务器客户端 socket operation on non-socket

12-09

server.c:rn#includern#includern#includern#includern#includern#includern#includern#includern#includern#include rn#include rnrnint main()rnrn int client_sockfd,server_sockfd;rn pid_t pid; rn int client_len,server_len;rn struct sockaddr_in client_add,server_add;rnrn if((server_sockfd = socket(AF_INET,SOCK_STREAM,0)) == -1) //创建服务端socket rn perror ("socket create fail");rn exit (EXIT_FAILURE); rn rn bzero(&server_add,sizeof(server_add));rn server_add.sin_family = AF_INET;rn server_add.sin_addr.s_addr = htonl(INADDR_ANY);rn server_add.sin_port = htons(9734);rn server_len = sizeof(server_add);rn //测试时服务端和客户端是在同一台机器上运行的,需使用setsockopt设置一下rn //允许重复使用本地地址和套接字绑定rn int j=1;rn setsockopt(server_sockfd,SOL_SOCKET,SO_REUSEADDR,&j,sizeof(j));rn if(bind(server_sockfd,(struct sockaddr *)&server_add,server_len) == -1) //给服务端套接字命名rn perror ("bind fail");rn exit (EXIT_FAILURE);rn rn listen(server_sockfd,5); //创建连接队列,开始等待客户连接,队列数为5rn signal(SIGCHLD,SIG_IGN); //忽略sigchld信号避免产生僵尸进程rn while(1)rn rn printf("server waiting\n");rn client_len = sizeof(client_add);rn client_sockfd = accept(server_sockfd,(struct sockaddr *)&client_sockfd,&client_len);rn if(client_sockfd == -1)rn rn perror("accept error:");rn exit(1);rn rn pid = fork();rn if(pid == 0)rn rn //没对client_sockfd读写,只是验证下socketrn close(client_sockfd);rn exit(0);rn rn else if(pid>0)rn close(client_sockfd);rn elsern perror("fork error");rn exit(1);rn rn rnrnclient.c:rn#includern#includern#includern#includern#includern#includern#includern#includern#include rn#include rnrnint main()rnrn int socketfd,len,result;rn struct sockaddr_in server_add;rn if((socketfd = socket(AF_INET,SOCK_STREAM,0)) == -1)rn rn perror ("socket create fail");rn exit (EXIT_FAILURE);rn rn bzero(&server_add,sizeof(server_add));rn server_add.sin_family = AF_INET;rn server_add.sin_addr.s_addr = inet_addr("127.0.0.1");rn server_add.sin_port = htons(9734);rn bzero(&(server_add.sin_zero),8) ;rn len = sizeof(server_add); rn result = connect(socketfd,(struct sockaddr *)&server_add,len);rn if (result == -1) rn perror ("connect server fail");rn exit (EXIT_FAILURE);rn rn //同样为对socketfd操作rn rn close(socketfd); //良好的习惯,一个套接字使用完要关闭rn exit (0);rnrnrn为了代码看起来更简短,对打开的sokcetfd我都没有去读写,原意是要发送接受文件。rn运行之后会出现socket operation on non-socket,网上说这个错误是=和==优先级问题,可我这份代码并无这样的问题,希望大神帮我下,卡一天了 论坛

linux socket服务器异步接收客户端数据

02-18

服务器程序使用linux c编写的,客户端使用Windows下的C#语言,在服务器中使用signal(SIGIO,handler)异步方式来接收客户端的请求,但是只有客户端的“连接请求”信号才能触发SIGIO信号,才能进入到handler处理函数中,其他来自客户端的数据请求不能触发SIGIO信号,因此也不能进入信号处理函数handler中,(也就是只能与客户端进行“握手”,不能接收到客户端的其他数据请求)。不知道跟signal函数有关还是跟SIGIO信号有关?请各位大神赐教,或者还有没有更好的办法rn下面是服务器的代码:rn/******************************************************************************rn* @attentionrn* rn* (c) Copyright 2015, Nanjing Kangni Mechanical & Electrical Co., Ltd.. All Rights Reserved.rn*rn*******************************************************************************rn* @Filename DSSCtrl.crn* @Author zhoujbrn* @Date 2015-11-16rn* @Version V001-000rn* @Descriptionrn* @Function Listrn* 1. .... rn*******************************************************************************rn* @Historyrn* 1. zhoujbrn* zhoujb, V001-000, 2015-11-16rn******************************************************************************/rnrn/******************************************************************************rn* Includesrn******************************************************************************/rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rn#include rnrn/******************************************************************************rn* Private macrorn******************************************************************************/rn#define PORT 4321rn#define BUFFER_SIZE 1024rn#define MAX_QUE_CONN_NM 5rn#define SEND_SIZE 1024rnrn/******************************************************************************rn* Private variablesrn******************************************************************************/rnrnrnstruct sockaddr_in server_sockaddr, client_sockaddr;rnint sin_size, recvbytes, sendbytes;rnint sockfd, client_fd;rnchar buf[BUFFER_SIZE];rnchar wuf[BUFFER_SIZE];rnrn/******************************************************************************rn* @Name accept_async()rn* @Description Async Handler of Signalrn* @Parametersrn* @Returnrn* @Historyrn* 1. Creatern* zhoujb, V001-000, 2015-12-2rn******************************************************************************/rnvoid accept_async(int sig_num)rnrn int i=0;rn sin_size = sizeof(client_sockaddr);rn rn printf("trying to connect\n");rn rn if((client_fd = accept(sockfd, (struct sockaddr *)&client_sockaddr, &sin_size)) == -1)rn rn perror("accept");rn exit(1);rn rn memset(buf, 0, sizeof(buf));rn rn if((recvbytes = recv(client_fd, buf, BUFFER_SIZE, 0)) == -1)rn rn perror("recv");rn exit(1);rn rn rn printf("Received a message: %d\n", buf[0]);rn rn if(buf[0] == 0x01)rn rnrn if(sendbytes = send(client_fd, buf, 1, 0) == -1)rn rn perror("send");rn exit(1);rn rn printf("hand shake sucessfully!\n");rnrn rn rn if(buf[0] ==0x02)rn rn if(sendbytes = send(client_fd, buf, 1, 0) == -1)rn rn perror("send");rn exit(1);rn rn printf("send sucessfully !\n");rn rn rn rn if(buf[0] == 3)rn rn while(1)rn rn sleep(1);rn if(sendbytes = send(client_fd, buf, 1, 0) == -1)rn rn perror("send");rn exit(1);rn rn i++;rn printf("send times is :%d ,buf is :%d\n",i,buf[0]);rn rn rn if(buf[0] == 4)rn rn printf("stop sending message!\n");rn exit(1);rn rn rnrnrn/******************************************************************************rn* Public functionsrn******************************************************************************/rnrn/******************************************************************************rn* @Name mainrn* @Description main taskrn* @Parametersrn* @Returnrn* @Historyrn* 1. Creatern* zhoujb, V001-000, 2015-11-23rn******************************************************************************/rnint main(int argc, char *argv[])rnrn int flags;rnrn rn if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)rn rn perror("socket");rn exit(1);rn rn printf("Socket id = %d\n", sockfd);rnrn server_sockaddr.sin_family = AF_INET;rn server_sockaddr.sin_port = htons(PORT);rn server_sockaddr.sin_addr.s_addr = INADDR_ANY;rn bzero(&(server_sockaddr.sin_zero), 8);rnrn int i = 1;rn setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));rnrn if(bind(sockfd, (struct sockaddr *)&server_sockaddr, sizeof(struct sockaddr)) == -1)rn rn perror("bind");rn exit(1);rn rn printf("Bind success!\n");rnrn if(listen(sockfd, MAX_QUE_CONN_NM) == -1)rn rn perror("listen");rn exit(1);rn rn printf("Listening........\n");rn signal(SIGIO, accept_async);rn fcntl(sockfd, F_SETOWN, getpid());rn flags = fcntl(sockfd, F_GETFL);rnrn if(flags < 0 || fcntl(sockfd, F_SETFL, flags | O_ASYNC) < 0)rn rn perror("funtl");rn rn rn while(1)rn rn sleep(2);rn printf("the task is working....\n"); rn rn rn close(sockfd);rn exit(0);rn exit(EXIT_SUCCESS); rn rn rn 论坛

没有更多推荐了,返回首页