隨後,我們在主程序中僅僅創建TcpListener類型實例,由於RemoteClIEnt類在構造函數中已經完成了 初始化的工作,所以我們在下面的while循環中我們甚至不需要調用任何方法:
class Server {
static void
Main(string[] args) {
Console.WriteLine("Server is running ... ");
IPAddress ip = new IPAddress(new byte[] { 127, 0, 0, 1 });
TcpListener listener = new TcpListener(ip, 8500);
listener.Start(); // 開始偵聽
Console.WriteLine("Start Listening ...");
while (true) {
// 獲取一個連接,同步方法,在此處中斷
TcpClient client = listener.AcceptTcpClIEnt();
RemoteClient wapper = new RemoteClient(clIEnt);
}
}
}
好了,服務端的實現現在就完成了,接下來我們再看一下客戶端的實現:
2.客戶端的實現
與服務端類似,我們首先對TcpClient進行一個簡單的包裝,使它的使用更加方便一些,因為它是服務 端的客戶,所以我們將類的名稱命名為ServerClIEnt:
public class ServerClIEnt {
private const int BufferSize = 8192;
private byte[] buffer;
private TcpClient clIEnt;
private NetworkStream streamToServer;
private string msg = "Welcome to TraceFact.Net!";
public ServerClIEnt() {
try {
client = new TcpClIEnt();
clIEnt.Connect("localhost", 8500); // 與服務器連接
} catch (Exception ex) {
Console.WriteLine(ex.Message);
return;
}
buffer = new byte[BufferSize];
// 打印連接到的服務端信息
Console.WriteLine("Server Connected!{0} --> {1}",
client.Client.LocalEndPoint, client.ClIEnt.RemoteEndPoint);
streamToServer = clIEnt.GetStream();
}
// 連續發送三條消息到服務端
public void SendMessage(string msg) {
msg = String.Format("[length={0}]{1}", msg.Length, msg);
for (int i = 0; i <= 2; i++) {
byte[] temp = Encoding.Unicode.GetBytes(msg); // 獲得緩存
try {
streamToServer.Write(temp, 0, temp.Length); // 發往服務器
Console.WriteLine("Sent: {0}", msg);
} catch (Exception ex) {
Console.WriteLine(ex.Message);
break;
}
}
lock (streamToServer) {
AsyncCallback callBack = new AsyncCallback(ReadComplete);
streamToServer.BeginRead(buffer, 0, BufferSize, callBack, null);
}
}
public void SendMessage() {
SendMessage(this.msg);
}
// 讀取完成時的回調方法
private void ReadComplete(IAsyncResult ar) {
int bytesRead;
try {
lock (streamToServer) {
bytesRead = streamToServer.EndRead(ar);
}
if (bytesRead == 0) throw new Exception("讀取到0字節");
string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received: {0}", msg);
Array.Clear(buffer, 0, buffer.Length); // 清空緩存,避免 髒讀
lock (streamToServer) {
AsyncCallback callBack = new AsyncCallback (ReadComplete);
streamToServer.BeginRead(buffer, 0, BufferSize, callBack, null);
}
} catch (Exception ex) {
if(streamToServer!=null)
streamToServer.Dispose();
clIEnt.Close();
Console.WriteLine(ex.Message);
}
}
}