UDP multicast

client/sender 不变,只需要把地D类广播组地址

server/revicer 需要添加结构体,设置socket

struct ip_mreq{
strtuct in_addr imr_multiaddr;
struct in_addr imr_interface;
};

struct ip_mreq multicastGroupInfo;
multicastGrouInfo.imr_multiaddrs.s_addr=inet_addr(multicastIPAddr);
multicastGroupInfo.imr_interface.s_addr=htonl(INADDR_ANY);

setsockopt(sock,IPPROTO_IP,IP_ADD_MEMBERSHIP,(void*)&multicastGroupInfo,sizefo(multicastGroupInfo))<0)

UDP broadcast

client和server都只需要添加一句
int boradcast=1;
if(setsockopt(sock,SOL_SOCKET,SO_BROADCAST,&broadcast,sizeof(broadcast)<0)
{
perror();

}

Thread

TCP 应用
client什么都不变
server在listen完后,while(1)中,accept()后,创建一个thread,在thread中通信,关闭通信

1
2
3
4
5
6
7
8
9
pthread_t threadId ;
while(1){
code = pthread_create ( &threadId, 0, thread_handler, ( void * ) &new ) ;
if ( code != 0 )
{
perror ( "Thread creation" ) ;
close ( new ) ;
exit ( 1 ) ;
}

pthread_create ( &threadId, 0, thread_handler, ( void ) &new ) ;
threadid是通过应用传递填充的thread id,0/null表示使用一个default 的 thread不加更改
main以外定义thread_ha ndler
(void
)&new 传给thread_handler参数
返回0成功

1
2
3
4
5
6
7
8
9
void * thread_handler ( void * threadSock )
{
int sock = * ( int * ) threadSock ;
int retThread ;

。。。
通信recv(),mirror(), send()
pthread_exit ( & retThread ) ;
}

thread跑完exit就行了

select

client不变,server bind地址后,初始化一个desctiptor sockets set
socket listen
在循环中,修改这个set