关闭

linux socket聊天程序

2108人阅读 评论(0) 收藏 举报

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);

        }

}  

 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:54052次
    • 积分:977
    • 等级:
    • 排名:千里之外
    • 原创:44篇
    • 转载:2篇
    • 译文:0篇
    • 评论:18条
    文章分类
    最新评论
    c加密
    #include void main() { char cc; printf("请输入一个字符: \n"); cc=getchar(); while(cc!='$') { if((cc<'A')||(cc>'z')) putchar(cc); else { cc=cc 13; putchar(cc); printf("\n"); } cc=getchar(); } }