linux进程实现聊天,linux下C语言实现的聊天小程序(转)

这是在CSDN上一网友贴出来的一小程序,用C语言实现,采用了多路I/O复用的方式实现并发服务器的功能.

一个服务器接收多个客户端的连接请求,某客户端发出向服务器发送的数据,服务器接收后都转发到其它的客户端,服务器不参与聊天的工作,只是完成了信息的转发功能.

哎,新浪的编辑器总是把C语言的注释代码给过滤掉,有点不爽!

//这是一本数上的例子,和你的功能一样.你的例子要改动的太大,偷懒一下.,下边一共5个文件,你弄好后,直接make就可以了,再把config内的ip和端口改一下运行就可以了

//采取的方式是这样的:server只起个中转作用,多clent连接上后,多个clent可以通过server交谈,server本身不参与交谈.

//用法:在一个终端或则后天提交server后,

//在多个终端分别运行clent交谈即可.

//------------------------------------server.c-----------------------------------------

#include

#include

#include "inet.h"

int init_ser( int);

int max( int

a, int b)

{

int themax;

if ( a

> b) themax = a;

else themax

= b;

return

themax;

}

void set_name( char *line, char *name)

{

strcpy(

name, &line[1]);

sprintf(

line, "%s join the room\n", name);

}

void add_name( char *line, char *name)

{

char theline[MAX_LINE];

strcpy(

theline, name);

strcat(

theline, " : ");

strcat(

theline, line);

strcpy(

line, theline);

}

int user_free( int user_link[MAX_CLIENT])

{

int i = 0;

while ( ( user_link[i] != 0)&&( i

if ( i == MAX_CLIENT) return( -1);

return( i);

}

void add_sockset( fd_set *sockset, int sockfd, int *user_link, int

*userfd)

{

int i;

FD_ZERO(

sockset);

FD_SET(

sockfd, sockset);

for ( i=0; i

if ( user_link[i] == 1) {

FD_SET( userfd[i], sockset);

}

}

}

int main(

void)

{

int sockfd;

int new_sockfd;

int user_link[MAX_CLIENT];

int userfd[MAX_CLIENT];

char username[MAX_CLIENT][MAX_NAME];

char line[MAX_LINE];

int userCount;

unsigned int cli_len;

struct sockaddr_in cli_addr;

FILE *file;

int port;

int length,

i, j;

fd_set sockset;

int maxfd =

0;

file =

fopen( "config", "r");

fgets( line,

MAX_LINE, file);

fscanf(

file, "%d", &port);

fclose(

file);

printf ( "%d

\n", port);

sockfd =

init_ser( port);

if ( sockfd == 0) {

printf( "Init server socket error\n");

fflush( stdout);

exit(1);

} //Socket init done

listen( sockfd, MAX_CLIENT);

cli_len = sizeof( cli_addr);

for ( i = 0; i

user_link[i] = 0;

username[i][0] = '\0';

}

userCount = 0;

FD_ZERO(

&sockset);

FD_SET(

sockfd, &sockset);

maxfd = max(

maxfd, sockfd+1);

for ( ; ;) {

select( maxfd, &sockset, NULL, NULL, NULL);

if ( FD_ISSET( sockfd, &sockset)

&& (userCount = user_free(

user_link)) >=0) {

new_sockfd = accept( sockfd, (struct

sockaddr*)&cli_addr,

&cli_len);

if ( new_sockfd < 0) {

user_link[userCount] = 0;

printf( "acc error\n");

} else {

user_link[userCount] = 1;

userfd[userCount] = new_sockfd;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值