快速业务通道

Linux 下tcp多线程编程

作者 佚名技术 来源 Linux系统 浏览 发布时间 2012-04-02

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));

Empire CMS,phome.net

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;

Empire CMS,phome.net

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

凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!

分享到: 更多

Copyright ©1999-2011 厦门凌众科技有限公司 厦门优通互联科技开发有限公司 All rights reserved

地址(ADD):厦门软件园二期望海路63号701E(东南融通旁) 邮编(ZIP):361008

电话:0592-5908028 传真:0592-5908039 咨询信箱:web@lingzhong.cn 咨询OICQ:173723134

《中华人民共和国增值电信业务经营许可证》闽B2-20100024  ICP备案:闽ICP备05037997号