|
|
Time server
Chap4_Ex15.cs
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class TimeServer {
private Socket s;
public TimeServer() {}
public bool StartUp(IPAddress ip, int port) {
try {
s = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Bind(new IPEndPoint(ip, port));
s.Listen(10);
} catch (Exception e) {
Console.WriteLine(e.Message);
return false;
}
for(;;) {
Socket newSocket = s.Accept(); // blocks until a client connects
Communicate(newSocket);
}
}
void Communicate(Socket clSock) {
try {
byte[] b = Encoding.ASCII.GetBytes(DateTime.Now.ToString());
clSock.Send(b);
clSock.Shutdown(SocketShutdown.Both);
clSock.Close ();
} catch (Exception e) {
Console.WriteLine(e.Message);
}
}
}
public class Chap4_Ex15_Test {
public static void Main(string[] args) {
TimeServer server = new TimeServer();
if (! server.StartUp(IPAddress.Loopback, 50000))
Console.WriteLine("Starting time server failed");
}
}
|
|