写一个C-S程序,实现简单的聊天功能。(tcp/ip)

client客户端处理器
#include
#include
#include
#include
#include
#include
#include
#include

int sockfd;/* 客户端socket /
char
IPADDR = “10.0.0.7”;/* 服务器的IP地址 /
short PORT = 6025;/
服务器服务端口 */
typedef struct sockaddr SA;
char name[30];

void init()
{
sockfd = socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in addr;
bzero(&addr,sizeof(struct sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
addr.sin_addr.s_addr = inet_addr(IPADDR);

	if (connect(sockfd,(SA*)&addr,sizeof(addr)) == -1)
{
    	perror("无法连接到服务器");
    	exit(-1);
	}
	printf("客户端启动成功\n");

}

void start()
{
pthread_t id;
void* recv_thread(void*);
pthread_create(&id,0,recv_thread,0);
char buf2[100] = {};
sprintf(buf2,"%s进入了聊天室",name);
send(sockfd,buf2,strlen(buf2),0);

	while(1)
{
	char buf[100] = {};
    	scanf("%s",buf);
    	char msg[131] = {};
    	sprintf(msg,"%s:%s",name,buf);
    	send(sockfd,msg,strlen(msg),0);
    	if (strcmp(buf,"bye") == 0)
	{
		memset(buf2,0,sizeof(buf2));
        		sprintf(buf2,"%s退出了聊天室",name);
        		send(sockfd,buf2,strlen(buf2),0);
        		break;
    	}
}
	close(sockfd);

}

void* recv_thread(void* p)
{
while(1)
{
char buf[100] = {};
if (recv(sockfd,buf,sizeof(buf),0) <= 0)
{
return;
}
printf("%s\n",buf);
}
}

int main()
{
init();
printf(“请输入您的名字:”);
scanf("%s",name);
start();
return 0;
}

service服务端
#include
#include
#include
#include
#include
#include

#define IPADDR “10.0.0.7”
#define PORT 6025

int listenfd; /* 服务器socket */
int sockfd = 0;

int main(int argc ,char **argv)
{
listenfd = socket(AF_INET,SOCK_STREAM,0);
if (listenfd == -1)
{
perror(“创建socket失败!!!”);
return -1;
}
struct sockaddr_in s_add, c_add;
bzero(&s_add,sizeof(struct sockaddr_in));
s_add.sin_family = AF_INET;
s_add.sin_port = htons(PORT);
s_add.sin_addr.s_addr = inet_addr(IPADDR);
int len = sizeof(s_add);

	if (bind(listenfd,(struct sockaddr*)&s_add,sizeof(struct sockaddr)) == -1)
{
    	perror("绑定失败");
    	return -1;
	}
	if (listen(listenfd,10) == -1)
{
    	perror("设置监听失败");
    	return -1;
	}

    if(-1 == (sockfd = accept(listenfd, (struct sockaddr*)&c_add, &sizeof(c_add) )))
    {
            perror("accept error 1");
            return -1;
    }
    printf("IP: %s connected !\n", inet_ntoa(c_add.sin_addr) );

printf("服务器启动成功\n");
	while(1)
{
            fd_set readfds;
            FD_ZERO(&readfds);
            FD_SET(0, &readfds);
            FD_SET(sockfd, &readfds);
            select(sockfd+1, &readfds, NULL, NULL, NULL);

            char buf[1024];
            if(FD_ISSET(0, &readfds))
            {
                    printf("input> ");fflush(stdout);
                    gets(buf);
                    write(sockfd, buf, sizeof buf);
            }
            if(FD_ISSET(sockfd, &readfds))
            {
                    read(sockfd, buf, sizeof buf);
                    printf("%s\n", buf);
            }
    }
    close(sockfd);

}

你可能感兴趣的:(Linux,vi)