先寫乙個客戶端,實現簡單的,能加入聊天,以及加入伺服器的介面。
#ifndef tcpclient_h有乙個加入伺服器的按鈕,還有乙個傳送訊息的按鈕,在標頭檔案,先定義兩個函式。#define tcpclient_h
#include #include #include #include #include #include #include #include class tcpclient : public qdialog
;#endif // tcpclient_h
#include "tcpclient.h"實現介面布局。在enter槽函式中,確定加入還是離開的伺服器的功能。如果加入了,就將訊息,寫到tcpsocket中,構造消。#include #include tcpclient::tcpclient(qwidget *parent,qt::windowflags f)
: qdialog(parent,f)
tcpclient::~tcpclient()
void tcpclient::slotenter()
if(usernamelineedit->text()=="")
username=usernamelineedit->text();
tcpsocket = new qtcpsocket(this);
connect(tcpsocket,signal(connected()),this,slot(slotconnected()));
connect(tcpsocket,signal(disconnected()),this,slot(slotdisconnected()));
connect(tcpsocket,signal(readyread()),this,slot(datareceived()));
tcpsocket->connecttohost(*serverip,port);
status=true;
}else
tcpsocket->disconnectfromhost();
status=false;
}}void tcpclient::slotconnected()
}void tcpclient::slotsend()
qstring msg=username+":"+sendlineedit->text();
tcpsocket->write(msg.tolatin1(),msg.length());
sendlineedit->clear();
}void tcpclient::slotdisconnected()
void tcpclient::datareceived()
}
服務端的標頭檔案:
#ifndef tcpserver_h這是服務端的介面的,把訊息顯示而已。實現這個布局。#define tcpserver_h
#include #include #include #include #include #include #include "server.h"
class tcpserver : public qdialog
;#endif // tcpserver_h
#include "tcpserver.h"建立tcp的套接字,以便實現服務端和客戶端的通訊。tcpserver::tcpserver(qwidget *parent,qt::windowflags f)
: qdialog(parent,f)
tcpserver::~tcpserver()
void tcpserver::slotcreateserver()
void tcpserver::updateserver(qstring msg,int length)
#ifndef tcpclientsocket_h以上是標頭檔案,具體的是:#define tcpclientsocket_h
#include #include class tcpclientsocket : public qtcpsocket
;#endif // tcpclientsocket_h
#include "tcpclientsocket.h"實現伺服器,標頭檔案:tcpclientsocket::tcpclientsocket()
void tcpclientsocket::datareceived()
}void tcpclientsocket::slotdisconnected()
#ifndef server_h#define server_h
#include #include #include "tcpclientsocket.h"
class server : public qtcpserver
;#endif // server_h
#include "server.h"實現後的介面:server::server(qobject *parent,int port)
:qtcpserver(parent)
void server::incomingconnection(int socketdescriptor)
void server::updateclients(qstring msg,int length)
}}void server::slotdisconnected(int descriptor)
}return;
}
socket網路程式設計TCP中C S架構函式框架
建立套接字 socket 填充伺服器網路資訊結構體 sockaddr in 將套接字與伺服器網路資訊結構體繫結 bind 將套接字設定為被動監聽狀態 listen 阻塞等待客戶端的連線請求 accept 進行通訊 recv send 建立套接字 socket 填充伺服器網路資訊結構體 sockadd...
Qt下TCP程式設計
一 伺服器 1 宣告乙個qtcpserver物件 qtcpserver serverlistener 2 new出物件 this serverlistener new qtcpserver 3 伺服器監聽 qhostaddress ipaddress 192.168.1.1 quint16 ippo...
Qt下TCP程式設計
一 伺服器 1 宣告乙個qtcpserver物件 qtcpserver serverlistener 2 new出物件 this serverlistener new qtcpserver 3 伺服器監聽 qhostaddress ipaddress 192.168.1.1 quint16 ippo...