client 使用Qt写的 远程的server使用 c语言写的 ubuntu 14.04 为什么 我只能连接一次 然后就断开连接了
if((socket_fd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
printf("socket create failed \n");
return -1;
}
memset(&mysocket,0,sizeof(mysocket));
mysocket.sin_family=AF_INET;
mysocket.sin_addr.s_addr=htonl(INADDR_ANY);
mysocket.sin_port=htons(PORT);
if(bind(socket_fd,(struct sockaddr*)&mysocket,sizeof(mysocket))==-1)
{
printf("bind error \n");
return -1;
}
if(listen(socket_fd,10)==-1)
{
printf("listen failed \n");
return -1;
}
printf("waiting for connect... \n");
while(1)
{
if((connect_fd=accept(socket_fd,(struct sockaddr*)NULL,NULL))==-1)
{
printf("accept error\n");
return -1;
}
n=recv(connect_fd,receive,BUFF,0);
if(!fork())
{
if(send(connect_fd,"Hello,you are connected!\n",26,0)==-1)
printf("send error\n");
printf("i have send \n");
close(connect_fd);
exit(0);
}
receive[n]='\0';
printf("you have reveived message %s\n",receive);
close(connect_fd);
}
close(socket_fd);
这是server端的测试程序
Widget::Widget(
QWidget *parent)
: QWidget(parent)
{
this->setFixedSize(300,500);
send=new QPushButton(this);
send->setText("发送消息");
send->setGeometry(250,400,40,20);
edit=new
QTextEdit(this);
edit->setGeometry(0,0,300,300);
line=new
QLineEdit(this);
line->setGeometry(0,350,400,20);
client=new QTcpSocket(this);
client->connectToHost(QHostAddress("115.29.99.220"),4321);
connect(client,SIGNAL(readyRead()),this,SLOT(get_message()));
connect(send,SIGNAL(clicked()),this,SLOT(send_message()));
}
void Widget::send_message()
{
qDebug()<<client->state();
int c=client->write(line->text().toStdString().c_str());
}
void Widget::get_message()
{
char temp[4096];
int n=client->read(temp,4096);
temp[n]='\0';
QString name(temp);
if(!name.isEmpty())
edit->setText(name);
}
这是client端
然后这是