日期:2014-05-16 浏览次数:20803 次
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <pthread.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
//person number who is chating
#define CHATNUM 8
int sd[CHATNUM];
// server send message that one client send to every client that online
void sendMsgToClient(int clientSocket)
{
char name[30];
char buffer[2048];
char temp[3000];
int i=0;
int returnValue=-1;
//get client's name
if((returnValue=recv(clientSocket,name,20,0))==-1)
{
perror("recv");
exit(1);
}
name[returnValue]=':';
name[returnValue]='\0';
printf("%s\n",name);
while(1)
{
//get the imformation that client send
returnValue=recv(clientSocket,buffer,1024,0);
if(returnValue==-1)
{
perror("recv");
exit(1);
}
//the client was offline
else if( returnValue==0)
{
printf("%sbye",name);
break;
}
/*
* find a socket that attact to client onlin
* send message to client online
*/
for(i=0;i<CHATNUM;i++)
{
if(sd[i]!=-1)
{
temp[0]='\0';
strcat(temp,name);
strcat(temp,buffer);
printf("%s\n",temp);
if(send(sd[i],temp,strlen(temp),0)==-1)
{
perror("send");
exit(1);
}
}
}
}
close(clientSocket);
for(i=0;i<CHATNUM;i++)
{
if(sd[i]==clientSocket)
{
sd[i]=-1;
}
}
pthread_exit(NULL);
}
int main()
{
int i=0;
int localSocket=0;
int clientSocket=0;
pthread_t pd;
struct sockaddr_in server_ip;
struct sockaddr_in client_ip;
socklen_t client_addr_size=0;
//init socket
memset(sd,-1,sizeof(sd));
if((localSocket=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("socket");
exit(1);
}
//set IP imformation
server_ip.sin_family=AF_INET;
server_ip.sin_port=htons(12345);
server_ip.sin_addr.s_addr=INADDR_ANY;
//bzero(&(server_ip.sin_zero),8);
if(bind(localSocket,(struct sockaddr *) &server_ip,\
sizeof(struct sockaddr ))==-1)
{
perror("bind");
exit(1);
}
if(listen(localSocket,10)==-1)
{
perror("listen");
exit(1);
}
while(1)
{
client_addr_size=sizeof(struct sockaddr_in);
if((clientSocket=accept(localSocket,(struct sockaddr *) &client_ip,\
&client_addr_size))==-1)
{
perror("accept");
exit(1);
}
//find a free socket
while(sd[i]==-1)
{
i=(i+1)%CHATNUM;
continue;
}
sd[i]=clientSocket;
pthread_create(&pd,NULL,(void *) sendMsgToClient,(int *)clientSocket);
}
return 0;
}
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <pthread.h>
void dellMsgFromServer(int sd)
{
char recvMsg[2000];
int recvMsgLen=0;
w