(原创)基于balckfin架构下的socket通信-客户端程序设计
0赞客户端程序新鲜出炉了........主要采用了OTIPIA提供的通信类完成的设计,我基本上没有参与,几个同学写出来的,很不错,鼓个掌!!!!
Qtopia提供了四个与套接字相关的类,分别说明如下:
a)QServerSocket类。它是基于TCP的服务器类,可以让它在指定端口上进行监听。它的API使用十分方便,调用构造函数,实现newConnection()成员函数来建立新连接即可。
b)QSocket类。它是具有缓冲的TCP连接类。
C)QSocketDevice类。它是独立于平台的低级别Socket—API类。
d)QSocketNotifier类。它是socket回调支持类,利用它可以在Qtopia中编写异步socket通信程序。一旦打开一个非阻塞式socket(如TCP、UDP等)或其他操作系统支持的协议族,就可以创建一QSoeketNotifier对象来监测套接字。当发生套接字事件时,将QSocketNotifier发出的activated()信号与希望被调用的槽连接。
客户端主要的代码如下:
(1)窗体函数
#include "win.h"
#include
#include
#include
#include
#include
char m_str[256];
/*
* Constructs a Form1 as a child of 'parent', with the
* name 'name' and widget flags set to 'f'.
*
* The dialog will by default be modeless, unless you set 'modal' to
* TRUE to construct a modal dialog.
*/
Form1::Form1( QWidget* parent, const char* name, WFlags fl )
: QWidget( parent, name, fl )
{
if ( !name )
setName( "Form1" );
textLabel1 = new QLabel( this, "textLabel1" );
textLabel1->setGeometry( QRect( 60, 60, 380, 50 ) );
languageChange();
resize( QSize(497, 314).expandedTo(minimumSizeHint()) );
timer_thread=new QTimer(this);
connect(timer_thread,SIGNAL(timeout()),SLOT(initthread()));
timer_thread->start(500,true);
timer=new QTimer(this);
connect(timer,SIGNAL(timeout()),SLOT(ontimer()));
timer->start(500,false);
}
/*
* Destroys the object and frees any allocated resources
*/
Form1::~Form1()
{
// no need to delete child widgets, Qt does it all for us
}
/*
* Sets the strings of the subwidgets using the current
* language.
*/
void Form1::languageChange()
{
setCaption( tr( "Form1" ) );
textLabel1->setText( tr( "textLabel1" ) );
}
void Form1::ontimer()
{
// while(1)
// {
printf("\n Now in function ontimer.\n");
textLabel1->setText( tr(m_str) );
// }
}
void * thread1(void * para)
{
int sockfd, numbytes;
char buf[MAXDATASIZE];
struct hostent *he;
struct sockaddr_in their_addr; // connector's address information
printf("\n Now in function thread1.\n");
if ((he=gethostbyname("192.168.1.196")) == NULL) { // get the host info
perror("gethostbyname");
exit(1);
}
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
their_addr.sin_family = AF_INET; // host byte order
their_addr.sin_port = htons(PORT); // short, network byte order
their_addr.sin_addr = *((struct in_addr *)he->h_addr);
memset(&(their_addr.sin_zero), '\0', 8); // zero the rest of the struct
if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1) {
perror("connect");
exit(1);
}
while (1)
{ memset(buf,0,sizeof(buf));
if ((numbytes=recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1)
{
perror("recv");
exit(1);
}
if (numbytes>0) {
buf[numbytes] = '\0';
printf("Received: %s\n",buf);
sprintf(m_str,"%s",buf);
}
else
break;
}
close(sockfd);
}
void Form1::initthread()
{
pthread_t th_a;
pthread_create(&th_a,NULL,thread1,NULL);
}
基本完成了,晚上把主函数写出来就算是大功告成了,发现了几个做工程好苗子,能吃苦,能钻研,是老师们最喜欢的!!