ASP.NET 是一个用于构建 Web 应用程序的框架,它基于 .NET 平台。实时显示服务器时间通常涉及到服务器端和客户端的交互,服务器端负责获取当前时间并将其发送到客户端,客户端则负责显示这个时间。
服务器端代码(C#):
using System;
using System.Web;
public partial class ServerTime : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(DateTime.Now.ToString());
}
}
客户端代码(HTML + JavaScript):
<!DOCTYPE html>
<html>
<head>
<title>Server Time</title>
<script>
function updateTime() {
fetch('/ServerTime.aspx')
.then(response => response.text())
.then(data => {
document.getElementById('serverTime').innerText = data;
});
}
setInterval(updateTime, 1000); // 每秒更新一次
</script>
</head>
<body>
<h1>Server Time: <span id="serverTime"></span></h1>
</body>
</html>
服务器端代码(C#):
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
public class WebSocketServer
{
private TcpListener _listener;
private WebSocketContext _context;
public async Task StartListening(int port)
{
_listener = new TcpListener(IPAddress.Any, port);
_listener.Start();
while (true)
{
var client = await _listener.AcceptTcpClientAsync();
_context = null;
var webSocket = await WebSocket.CreateFromStreamAsync(client.GetStream(), true, null, TimeSpan.FromMilliseconds(500));
_context = new WebSocketContext(webSocket);
await Echo();
}
}
private async Task Echo()
{
byte[] buffer = new byte[1024 * 4];
while (true)
{
var result = await _context.WebSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close)
{
break;
}
var message = Encoding.UTF8.GetString(buffer, 0, result.Count);
var response = DateTime.Now.ToString();
await _context.WebSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(response)), result.MessageType, result.EndOfMessage, CancellationToken.None);
}
}
}
客户端代码(HTML + JavaScript):
<!DOCTYPE html>
<html>
<head>
<title>Server Time</title>
<script>
const socket = new WebSocket('ws://localhost:8080');
socket.onopen = () => {
console.log('Connected to server');
};
socket.onmessage = (event) => {
document.getElementById('serverTime').innerText = event.data;
};
socket.onclose = () => {
console.log('Disconnected from server');
};
</script>
</head>
<body>
<h1>Server Time: <span id="serverTime"></span></h1>
</body>
</html>
通过以上方法,你可以实现 ASP.NET 实时显示服务器时间的功能,并根据具体需求选择合适的实现方式。
领取专属 10元无门槛券
手把手带您无忧上云