linux socket聊天程序

socket.h

#include<stdio.h>                                                                                   
#include<pthread.h>
#include<time.h>
#include<sys/select.h>
#include<signal.h>
#include<sys/un.h>
#include<unistd.h>
#include<sys/uio.h>
#include<errno.h>
#include<pthread.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<sys/time.h>
#include<netinet/in.h>
#include<sys/wait.h>
#include<stdlib.h>
#include<netdb.h>
#include<arpa/inet.h>

client.c

#include "socket.h"

int main()
{
        int c_socket;
        int c_accept;
        int c_read;
        int backlog = 10;
        char mes[512],buffer[512],clientname[20];
        int len_c=sizeof(struct sockaddr);
        struct sockaddr_in c_sock;
        bzero(mes, sizeof(mes));
                                               
        c_socket=socket(AF_INET,SOCK_STREAM,0);
        if(c_socket==-1)
        {  
                printf("socket");
        }

       c_sock.sin_family=AF_INET;
       c_sock.sin_port=htons(5000);
       c_sock.sin_addr.s_addr=inet_addr("127.0.0.1");

      if((connect(c_socket, (struct sockaddr*)& c_sock, len_c)) == -1)
      {
               printf("connect!");
      }

      while(fgets(mes, sizeof(mes), stdin) != NULL)
     {
           write(c_socket, mes, sizeof(mes));
           read(c_socket, buffer, sizeof(buffer));
           printf("%s",buffer);
           memset(buffer,512,0);
     }
}
 

server.c

#include "socket.h"

int main()
{
        int c_socket;
        int c_accept;
        int c_read;
        int backlog = 10;
        char mes[512],buffer[512],clientname[20];
        int len_c=sizeof(struct sockaddr);
        struct sockaddr_in c_sock;
        bzero(mes, sizeof(mes));
       
        c_socket=socket(AF_INET,SOCK_STREAM,0);
        if(c_socket==-1)
        {  
                printf("socket");
        }

        c_sock.sin_family=AF_INET;
        c_sock.sin_port=htons(5000);
        c_sock.sin_addr.s_addr=inet_addr("127.0.0.1");

        if((bind(c_socket, (struct sockaddr*)& c_sock, len_c)) == -1)
        {
                printf("bind!");
        }

        if((listen(c_socket, backlog)) == -1)
        {
                printf("listen");
        }

        for( ; ;)
        {
                if((c_accept = accept(c_socket, (struct sockaddr*)& c_sock, &len_c)) == -1)
                {
                        printf("accept");
                }

               
                while((c_read = read(c_accept, mes, sizeof(mes))) > 0)
                        write(c_accept, mes, c_read);

        }

}  

 

阅读更多
个人分类: 代码
想对作者说点什么? 我来说一句

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

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭