/* ************************************************************************
* Filename: qq_thread.c
* Description:
* Version: 1.0
* Created: 2010年07月16日 17时03分34秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
//接收线程:负责接收消息并显示
void *recv_thread(void*arg)
{
int udpfd = (int)arg;
struct sockaddr_in addr={AF_INET};
socklen_t addrlen = sizeof(addr);
while(1)
{
char buf[200]="";
recvfrom(udpfd, buf, 100, 0, (struct sockaddr*)&addr, &addrlen);
printf("/r/033[31m[%s]:/033[32m%s/n",inet_ntoa(addr.sin_addr),buf);
write(1,"UdpQQ:",6);
}
return NULL;
}
int main()
{
char buf[100]="";
int i =1;
int udpfd;
pthread_t tid;
struct sockaddr_in addr={AF_INET};
int addrlen = sizeof(addr);
addr.sin_port = htons(8000);
addr.sin_addr.s_addr = INADDR_ANY;
//创建套接口
if((udpfd=socket(AF_INET,SOCK_DGRAM, 0))<0)
{
perror("socket");
exit(1);
}
//设置端口
if(bind(udpfd, (struct sockaddr*)&addr, sizeof(addr))<0)
{
perror("bind");
exit(1);
}
printf("input: /"say 192.168.220.X/" to sendmsg to somebody/n");
//创建接收线程
pthread_create(&tid, NULL, recv_thread, (void*)udpfd);
printf("/033[32m");
fflush(stdout);
while(1)
{ //主线程负责发送消息
write(1,"UdpQQ:",6);
fgets(buf, 100, stdin);
buf[strlen(buf)-1]='/0';
if(strncmp(buf, "sayto", 5)==0)
{
addr.sin_addr.s_addr = inet_addr(buf+6);
printf("/rsayto %s/n",inet_ntoa(addr.sin_addr));
continue;
}
else if(strcmp(buf, "exit")==0)
{
close(udpfd);
exit(1);
}
sendto(udpfd, buf, strlen(buf),0,(struct sockaddr*)&addr, sizeof(addr));
}
return 0;
}