接下來,再用NetworkStream 讀消息:
一旦我們收到消息後,我們就可以做任何想做的了:
txtStatus.Text += "\r\n" + strDisplayMessageType + strWriteText.TrimStart(new char []{'\r','\n'});
我的SocketServer 類使用一些事件,這樣使得coding變得更容易:
public event ClientConnectedEventHandler ClIEntConnected;
public event ClientDisconnectingEventHandler ClIEntDisconnecting;
public event MessageReceivedEventHandler MessageReceived;
[客戶端]
客戶端基本上與上面一樣,創建一個包含TCPListener 的ClIEntSocket ,然後調用其Connect() 方法 :
IPEndPoint serverEndpoint = new IPEndPoint (ipaAddress , iPort);
tcpClient = new TcpClIEnt ();
tcpClIEnt.Connect(serverEndpoint);
thrListenForMessages = new Thread (new ThreadStart(ListenForMessages));
thrListenForMessages.Start();
ListenForMessages 會循環NetworkStream.Read()
然後,我們做一些處理,把得來的數據發送一個Message:
另外,我的目標是創建一個象YM/MSN 一樣的即時通訊軟件,所以,我做了兩個UI form: MessengerForm 和ClientWindow。MessengerForm 包含ClIEntSocket ,並接收消息。根據接收到的消息 ,調用MessengerWindow 顯示文字。
提示:文章中通過Invoke調用界面:
this.Invoke(createNewClIEntDelegate, new object []{receivedMessage});