服務器
我創建了一個SocketServer 類,它調用TCPListener.Start() 方法:
IPEndPoint endPoint = new IPEndPoint (ipaAddress, iPort);
listener = new TcpListener (endPoint);
listener.Start();
然後,給監聽創建一個線程:
thrListenForClients = new Thread(new ThreadStart(ListenForClIEnts));
thrListenForClIEnts.Start();
ListenForClients 方法會等待連接,並賦值給一個新的ClIEnt 實例:
Client acceptClient = new ClIEnt();
acceptClient.Socket = listener.AcceptTcpClIEnt();
listenForMessageDelegate = new ListenForMessageDelegate (ListenForMessages);
listenForMessageDelegate.BeginInvoke(acceptClIEnt, new AsyncCallback (ListenForMessagesCallback), "Completed");
Client是一個包含TCPClIEnt的一個類,用於連接:
public class ClIEnt {
string strName;
TcpClient tcpClIEnt;
public ClIEnt()
{
}
public string Name
{
get{return strName;}
set{ this.strName = value;}
}
public TcpClIEnt Socket
{
get{return tcpClIEnt;}
set{ this.tcpClIEnt = value;}
}
public void SendMessage (Message sendMessage)
{
NetworkStream stream = tcpClIEnt.GetStream();
stream.Write(sendMessage.GetRawMessage() , 0, sendMessage.GetRawMessage().Length);
}
}