iSize = sizeof(SerAddr);
serfd = socket(PF_INET,SOCK_STREAM,0);
if (0 > serfd)
{
printf("init socket failed:%dn",serfd);
return 0;
}
memset(&(SerAddr),0x00,sizeof(struct sockaddr_in));
memset(&(CliAddr),0x00,sizeof(struct sockaddr_in));
SerAddr.sin_family = AF_INET;
SerAddr.sin_port = htons(PORT);
SerAddr.sin_addr.s_addr = htonl(INADDR_ANY);
if ( 0 > bind(serfd,(struct sockaddr *)&SerAddr,iSize))
{
printf("server bind to port %d failed n",PORT);
return 0;
}
if ( 0 > setsockopt(serfd,SOL_SOCKET,SO_RCVBUF,&bufSize,sizeof(bufSize)))
{
printf("setsockopt error:%s",strerror(errno));
return -1;
}
if (0 > listen(serfd,MAX_LISTEN))
{
printf("listen failedn");
return 0;
}
while(1)
{
clfd = accept(serfd,(struct sockaddr *)&CliAddr,&iSize);
if (0 > clfd)
{
printf("accept failed %s",strerror(errno));
sleep(1);
continue;
}
if (count < 256)
{
pthread_create(&tid[count ],&attr,recv_msg,(void *)&clfd);
}
else
{
printf("nntoo many threads nn");
return - 1;
}
}
pthread_mutex_destroy(&mutex);
pthread_attr_destroy(&attr);
return 0;
}
/* 客户端 */
/* 编译命令 gcc -Wall -g -o client client.c */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <errno.h>
#include <ctype.h>
typedef struct MsgHead{
unsigned char type;
unsigned char BL[4];
}MH;
int con_serv()
{
struct sockaddr_in SerAddr;
int tcpfd = -1,iPort = 8458,iCount = 0;
char sIP[64] = {""};
int sndBufSize = 4 * 1024 * 1024;
tcpfd = socket(AF_INET,SOCK_STREAM,0);
if(tcpfd < 0)
{
printf("socket error:%sn",strerror(errno));
return -1;
}
if ( 0 > setsockopt(tcpfd, SOL_SOCKET, SO_SNDBUF, (char *)&sndBufSize, sizeof(sndBufSize)))
{
printf("make_tcp(): setsockopt failed for server addressn");
return -1;
}
memset(&(SerAddr),0x00,sizeof(SerAddr));
memset(sIP,0x00,sizeof(sIP));
strcpy(sIP,"127.0.0.1");
SerAddr.sin_family = AF_INET;
SerAddr.sin_port = htons(iPort);
SerAddr.sin_addr.s_addr = inet_addr(sIP);
for (iCount = 0; iCount < 3; iCount )
{
if (0 > connect(tcpfd,(struct sockaddr *)&SerAddr,sizeof(struct sockaddr)))
{
printf("the %d times connect to machine: %s,port:%d failed n",iCount 1,sIP,iPort);
}
else
{
return tcpfd;
}
}
return -1;
}
void tcp_send(int tcpfd,int num)
{
fd_set wset;
struct timeval tv = {1,0};
int i = 0,iRet = -1;
char buf[128] = {"&q |