461
Chương 11: Lập trình mạng
using System.Threading;
using SharedComponent;
public class ClientHandler {
private TcpClient client;
private string ID;
public ClientHandler(TcpClient client, string ID) {
this.client = client;
this.ID = ID;
}
public void Start() {
// Thu lấy network stream.
NetworkStream stream = client.GetStream();
// Tạo BinaryWriter để ghi ra stream.
BinaryWriter w = new BinaryWriter(stream);
// Tạo BinaryReader để đọc từ stream.
BinaryReader r = new BinaryReader(stream);
if (r.ReadString() == ClientMessages.RequestConnect) {
w.Write(ServerMessages.AcknowledgeOK);
Console.WriteLine(ID + ": Connection completed.");
while (r.ReadString() != ClientMessages.Disconnect) {}
Console.WriteLine(ID + ": Disconnect request received.");
w.Write(ServerMessages.Disconnect);
}else {
Console.WriteLine(ID + ": Could not complete connection.");
}