Real time Application 即時申請技術在本文裡是作為一個執行個體來示範在使用者(Tcpclient)申請與伺服器(TcpServer)申請之間使用Socket類的情況 。該項目同樣也示範在即時項目中如何使用listview控制以及如何傳遞XML格式資訊。
TcpServer.exe 檔顯示了在單獨的thread當中(而不是在GUI 線程之中)TCP socket的相互連訊。
TcpClient.exe檔案同樣也使用一條單獨的線程 從Socket中讀取資料,然後對錶單中的list view控制項進行更新。
步聚如下:
1.TcpServer 監聽連接埠8002,並且發射線程等待用戶端連結。
Hashtable socketHolder = new Hashtable();
Hashtable threadHolder = new Hashtable();
public Form1()
{
// Required for Windows Form Designer support
//
InitializeComponent();
tcpLsn = new TcpListener(8002);
tcpLsn.Start();
// tcpLsn.LocalEndpoint may have a bug, it only show 0.0.0.0:8002
stpanel.Text = "Listen at: " + tcpLsn.LocalEndpoint.ToString();
Thread tcpThd = new Thread(new ThreadStart(WaitingForClient));
threadHolder.Add(connectId, tcpThd);
tcpThd.Start() ;
}2. TcpClient與TcpSrv串連上後,發送用戶端參考資料集至TcpServer,然後發射線程,該線程是用來接收通過Socket傳來的資料。
private void menuConn_Click(object sender, System.EventArgs e)
{
ConnectDlg myDlg = new ConnectDlg();
myDlg.ShowDialog(this);
if( myDlg.DialogResult==DialogResult.OK)
{
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp );
IPAddress hostadd = IPAddress.Parse(myDlg.IpAdd);
int port=Int32.Parse(myDlg.PortNum);
IPEndPoint EPhost = new IPEndPoint(hostadd, port);
Try
{
s.Connect(EPhost);
if (s.Connected)
{
Byte[] bBuf;
string buf;
buf = String.Format("{0}:{1}", myDlg.UserName,myDlg.PassWord);
bBuf=ASCII.GetBytes(buf);
s.Send(bBuf, 0 , bBuf.Length,0);
t = new Thread(new ThreadStart(StartRecieve));
t.Start();
sbar.Text="Ready to recieve data";
}
}
catch (Exception e1)
{
MessageBox.Show(e1.ToString());
}
}
}
private void StartRecieve()
{
miv = new MethodInvoker(this.UpdateListView);
int cnt=0;
string tmp=null;
Byte[] firstb= new Byte[1];
while (true)
{
try
{
Byte[] receive = new Byte[1];
int ret = s.Receive(receive, 1, 0);
if (ret > 0)
{
switch(receive[0])
{
case 11: //check start message
cnt=0;
break;
case 10: // check end message
cnt=0;
if(firstb[0] == ':')
HandleCommand(tmp);
else if(firstb[0] == '<')
HandleXml(tmp);
else
HandleText(tmp);
tmp=null;
break;
default:
if (cnt == 0)
firstb[0] = receive[0];
tmp += System.Text.Encoding
.ASCII.GetString(receive);
cnt++;
break;
}
}
}
catch (Exception e)
{
if( !s.Connected )
{
break;
}
}
}
t.Abort();
}3.TcpServer接收來自TcpClient的串連請求,並且將socket 執行個體儲存到Hash表中,然後發射線程以便控制socket的通訊,同時將用戶端資訊在listview 控制項中顯示出來。