UDP 聊天室


      学过Socket编程,连个UDP聊天室也没写过实在是说不过去了。写个简单的聊天室。客户端通过向服务器发送数据进行对话。所有信息在服务端显示。

   运行效果:

 

   服务端:

[fsy@localhost my_socket]$ ./udps
create socket.
bind address to socket.
fsy said: i'm coming~

saosao123 said: leave me alone

fsy said: come baby

saosao123 said: who r u ?

fsy said: just guess~

Teacher said: shut up u guys

 

客户端:

[fsy@localhost my_socket]$ ./udpc 192.168.189.13 saosao123
create socket.
Welcome Mr. saosao123!
leave me alone
who r u ?

 


服务端程序:

 

include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

int main(int argc, char **argv){
    struct sockaddr_in s_addr,c_addr;
    int sock;
    socklen_t addr_len;
    int len;
    char buff[128];

    if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
        perror("socket");
        exit(errno);
    } else
        printf("create socket.\n\r");

    memset(&s_addr, 0, sizeof(struct sockaddr_in));

    s_addr.sin_family = AF_INET;
    s_addr.sin_port = htons(7838);
    s_addr.sin_addr.s_addr = INADDR_ANY;

    if ((bind(sock, (struct sockaddr *) &s_addr, sizeof(s_addr))) == -1) {
        perror("bind");
        exit(errno);
    } else
        printf("bind address to socket.\n\r");

    addr_len = sizeof(c_addr);
    while (1) {
        len = recvfrom(sock, buff, sizeof(buff) - 1, 0, (struct sockaddr *) &c_addr, &addr_len);
        if (len < 0) {
            perror("recvfrom");
            exit(errno);
        }
        buff[len] = '\0';
        printf("%s\n", buff);
    }
    return 0;
}


 

客户端程序:

 

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

int main(int argc, char **argv){
    struct sockaddr_in s_addr;
    int sock;
    int addr_len;
    int len;
    char buff[128];
    char message[128];

    if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
        perror("socket");
        exit(errno);
    } else
        printf("create socket.\n\r");

    s_addr.sin_family = AF_INET;
    s_addr.sin_port = htons(7838);
    if (argc==3){
        s_addr.sin_addr.s_addr = inet_addr(argv[1]);
    }
    else {
        printf("Usage: %s  !\n");
        exit(0);
    }
    printf("Welcome Mr. %s!\n",argv[2]);
    while(1){
        memset(buff,0,sizeof(buff));
        memset(message,0,sizeof(message));
        //这里为了连接字符串又弄了一个buff,应该有更好的办法,望路过的高手赐教
        strcpy(buff,argv[2]);
        strcat(buff," said: ");
        fgets(message,128,stdin);
        strcat(buff,message);
        addr_len = sizeof(s_addr);
        len = sendto(sock, buff, strlen(buff), 0, (struct sockaddr *) &s_addr, addr_len);
        if (len < 0) {
            printf("\n\rsend error.\n\r");
            return 1;
        }
    }
    return 0;
}


 

 本篇博客出自  阿修罗道,转载请注明出处:http://blog.csdn.net/fansongy/article/details/6924011

 

你可能感兴趣的:(linux,计算机网络,聊天,socket,struct,include,server,服务器)