当然, 我可以为您创建一个使用 Bun 运行时, 基于 TypeScript 和 WebSocket 的天气预报例程。这个例子将包括一个 WebSocket 服务器, 它每隔一段时间发送模拟的天气数据, 以及一个简单的客户端来接收和显示这些数据。

首先, 让我们创建服务器端代码:

  1. 创建一个新的项目目录并初始化:
mkdir weather-forecast
cd weather-forecast
bun init
  1. 安装必要的依赖:
bun add ws @types/ws
  1. 创建一个 server.ts 文件:
import { WebSocket, WebSocketServer } from 'ws';
 
interface WeatherData {
  temperature: number;
  humidity: number;
  windSpeed: number;
  condition: string;
}
 
const wss = new WebSocketServer({ port: 8080 });
 
const conditions = ['Sunny', 'Cloudy', 'Rainy', 'Windy', 'Snowy'];
 
function generateWeatherData(): WeatherData {
  return {
    temperature: Math.round((Math.random() * 30 + 10) * 10) / 10, // 10 to 40 celsius
    humidity: Math.round(Math.random() * 100),
    windSpeed: Math.round(Math.random() * 20 * 10) / 10,
    condition: conditions[Math.floor(Math.random() * conditions.length)],
  };
}
 
wss.on('connection', (ws: WebSocket) => {
  console.log('Client connected');
 
  const interval = setInterval(() => {
    const weatherData = generateWeatherData();
    ws.send(JSON.stringify(weatherData));
  }, 5000); // Send weather update every 5 seconds
 
  ws.on('close', () => {
    console.log('Client disconnected');
    clearInterval(interval);
  });
});
 
console.log('WebSocket server is running on ws://localhost:8080');

这个服务器每 5 秒生成一次模拟的天气数据并发送给所有连接的客户端。

  1. 现在, 让我们创建一个简单的 HTML 客户端。创建一个 index.html 文件:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Weather Forecast</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f0f0f0;
        }
        #weather-data {
            background-color: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>
    <div id="weather-data">
        <h2>Current Weather</h2>
        <p>Temperature: <span id="temperature"></span>°C</p>
        <p>Humidity: <span id="humidity"></span>%</p>
        <p>Wind Speed: <span id="wind-speed"></span> km/h</p>
        <p>Condition: <span id="condition"></span></p>
    </div>
 
    <script>
        const ws = new WebSocket('ws://localhost:8080');
 
        ws.onmessage = (event) => {
            const weatherData = JSON.parse(event.data);
            document.getElementById('temperature').textContent = weatherData.temperature;
            document.getElementById('humidity').textContent = weatherData.humidity;
            document.getElementById('wind-speed').textContent = weatherData.windSpeed;
            document.getElementById('condition').textContent = weatherData.condition;
        };
 
        ws.onerror = (error) => {
            console.error('WebSocket Error:', error);
        };
 
        ws.onclose = () => {
            console.log('WebSocket connection closed');
        };
    </script>
</body>
</html>
  1. 运行服务器:
bun run server.ts
  1. 打开 index.html 文件在浏览器中查看结果。

这个例程演示了如何使用 Bun 运行时和 TypeScript 创建一个 WebSocket 服务器, 以及如何创建一个简单的客户端来接收和显示实时更新的天气数据。

要进一步改进这个例程, 你可以考虑:

  1. 使用真实的天气 API 来获取实际的天气数据。
  2. 添加错误处理和重连逻辑。
  3. 实现用户认证以提供个性化的天气预报。
  4. 添加更多的天气相关信息, 如预报、警报等。
  5. 优化客户端的 UI/UX, 使用图标来表示天气状况。
  6. 实现地理位置检测, 自动为用户提供其所在位置的天气信息。

这个例子为你提供了一个基础, 你可以在此基础上构建更复杂和功能丰富的实时天气应用。

再来一个实现的案例

好的, 我来为您编写一个使用 Bun 运行时、TypeScript 和 WebSocket 的天气预报示例。这个例子将创建一个 WebSocket 服务器, 客户端可以连接并接收定期更新的天气预报信息。

首先, 创建一个新的 TypeScript 项目并安装必要的依赖:

mkdir weather-forecast
cd weather-forecast
bun init -y
bun add @types/ws

然后, 创建一个 server.ts 文件, 包含以下代码:

import { Server } from "bun";
 
interface WeatherData {
  temperature: number;
  condition: string;
}
 
const weatherConditions = ["Sunny", "Cloudy", "Rainy", "Windy", "Snowy"];
 
function getRandomWeather(): WeatherData {
  return {
    temperature: Math.floor(Math.random() * 35) + 5, // 5 to 40 degrees
    condition: weatherConditions[Math.floor(Math.random() * weatherConditions.length)]
  };
}
 
const server = Bun.serve({
  port: 3000,
  fetch(req, server) {
    if (server.upgrade(req)) {
      return; // Upgrade to WebSocket
    }
    return new Response("Hello via HTTP!");
  },
  websocket: {
    open(ws) {
      console.log("Client connected");
      
      // Send weather updates every 5 seconds
      const intervalId = setInterval(() => {
        const weather = getRandomWeather();
        ws.send(JSON.stringify(weather));
      }, 5000);
 
      // Store the interval ID so we can clear it when the connection closes
      ws.data = { intervalId };
    },
    close(ws) {
      console.log("Client disconnected");
      // Clear the interval when the connection closes
      clearInterval(ws.data.intervalId);
    },
    message(ws, message) {
      console.log(`Received message: ${message}`);
    },
  },
});
 
console.log(`WebSocket server listening on port ${server.port}`);

这个服务器将:

  1. 在端口 3000 上启动一个 WebSocket 服务器
  2. 当客户端连接时, 每 5 秒发送一次随机生成的天气数据
  3. 当客户端断开连接时, 停止发送天气更新

现在, 创建一个简单的 HTML 客户端文件 client.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Weather Forecast</title>
</head>
<body>
    <h1>Weather Forecast</h1>
    <div id="weather"></div>
 
    <script>
        const socket = new WebSocket('ws://localhost:3000');
 
        socket.onmessage = function(event) {
            const weather = JSON.parse(event.data);
            document.getElementById('weather').innerHTML = `
                Temperature: ${weather.temperature}°C<br>
                Condition: ${weather.condition}
            `;
        };
 
        socket.onclose = function(event) {
            document.getElementById('weather').innerHTML = 'Connection closed';
        };
    </script>
</body>
</html>

要运行这个例子:

  1. 启动服务器:

    bun run server.ts
    
  2. 在浏览器中打开 client.html 文件

你应该能看到每 5 秒更新一次的天气预报信息。

这个例子展示了如何使用 Bun、TypeScript 和 WebSocket 创建一个简单的实时天气预报服务。你可以进一步扩展它, 例如添加真实的天气 API 数据, 实现错误处理, 或添加更多的客户端交互功能。

GPT-40 生成的例子

当使用 TypeScript 编写 WebSocket 服务来实现天气预报的例程时,我们将使用一个简单的示例来演示如何通过 WebSocket 从服务器端向客户端发送实时天气信息。我们假设你已经有一个天气数据源,并能通过 WebSocket 将这些数据推送到客户端。

项目结构

首先,我们来创建项目的基本结构:

  1. 安装依赖:我们将使用 ws 库来处理 WebSocket 连接。
  2. 实现服务端:创建一个 WebSocket 服务器,它可以接收客户端连接,并向客户端推送天气数据。

步骤

1. 准备工作

确保你的开发环境中安装了 Node. Js 和 npm。

npm init -y
npm install ws typescript @types/node --save-dev

2. 编写 TypeScript 代码

创建 server.ts 文件,这里是服务端的代码:

import WebSocket from 'ws';
 
// 模拟的天气数据
const weatherData = [
    { city: 'New York', temperature: 28, condition: 'Sunny' },
    { city: 'London', temperature: 18, condition: 'Cloudy' },
    { city: 'Tokyo', temperature: 30, condition: 'Rainy' }
];
 
// 创建 WebSocket 服务器
const wss = new WebSocket.Server({ port: 8080 });
 
console.log('WebSocket server running on ws://localhost:8080');
 
// 监听连接事件
wss.on('connection', (ws: WebSocket) => {
    console.log('Client connected');
 
    // 每隔一段时间发送一次随机天气数据
    const interval = setInterval(() => {
        const randomIndex = Math.floor(Math.random() * weatherData.length);
        const data = weatherData[randomIndex];
        ws.send(JSON.stringify(data));
    }, 3000);
 
    // 监听客户端关闭连接
    ws.on('close', () => {
        console.log('Client disconnected');
        clearInterval(interval);
    });
});

3. 编译和运行

package.json 中添加 TypeScript 编译脚本:

"scripts": {
    "start": "tsc && node dist/server.js"
},

然后,运行以下命令来编译 TypeScript 并启动服务器:

npm start

客户端代码

现在,让我们创建一个简单的 HTML 文件作为 WebSocket 客户端 index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Weather Client</title>
</head>
<body>
    <h1>Weather Updates</h1>
    <ul id="weather-list"></ul>
 
    <script>
        const socket = new WebSocket('ws://localhost:8080');
 
        socket.onmessage = function(event) {
            const weatherData = JSON.parse(event.data);
            const weatherList = document.getElementById('weather-list');
            const newItem = document.createElement('li');
            newItem.textContent = `${weatherData.city}: ${weatherData.temperature}°C, ${weatherData.condition}`;
            weatherList.appendChild(newItem);
        };
    </script>
</body>
</html>

总结

这个例子展示了如何使用 TypeScript 和 WebSocket 实现一个简单的天气预报系统。服务器定期发送随机的天气数据到客户端,客户端通过 WebSocket 接收并显示这些数据。你可以根据实际需求修改和扩展这个示例,例如通过接入真实的天气 API 来获取实际的天气数据。

DeepSeek 生成的例子

好的,下面是一个使用 Bun 运行时和 TypeScript 编写的 WebSocket 服务示例,用于提供天气预报信息。这个示例假设你已经安装了 Bun 和 TypeScript。

首先,确保你已经安装了 Bun 和 TypeScript。如果没有安装,可以通过以下命令安装:

curl -fsSL https://bun.sh/install | bash
npm install -g typescript

接下来,创建一个新的 TypeScript 项目并初始化:

mkdir weather-websocket
cd weather-websocket
npm init -y
tsc --init

然后,安装所需的依赖:

bun install ws

在项目根目录下创建一个 src 文件夹,并在其中创建一个 index.ts 文件:

// src/index.ts
import { WebSocketServer } from 'ws';
 
const wss = new WebSocketServer({ port: 8080 });
 
wss.on('connection', (ws) => {
  ws.on('message', (message) => {
    console.log(`Received message: ${message}`);
    if (message === 'weather') {
      const weatherData = {
        city: 'New York',
        temperature: '20°C',
        condition: 'Sunny'
      };
      ws.send(JSON.stringify(weatherData));
    }
  });
 
  ws.send('Welcome to the weather WebSocket server');
});
 
console.log('WebSocket server started on port 8080');

接下来,修改 tsconfig.json 文件,确保编译后的 JavaScript 文件输出到 dist 文件夹:

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "CommonJS",
    "outDir": "./dist",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src"]
}

然后,编译 TypeScript 代码:

tsc

最后,使用 Bun 运行编译后的 JavaScript 代码:

bun run dist/index.js

现在,你的 WebSocket 服务器已经启动并在端口 8080 上监听连接。你可以使用任何 WebSocket 客户端连接到这个服务器并发送消息。例如,使用 wscat 工具:

npm install -g wscat
wscat -c ws://localhost:8080

连接成功后,发送 weather 消息:

> weather

服务器将返回天气预报数据:

{
  "city": "New York",
  "temperature": "20°C",
  "condition": "Sunny"
}

这样,你就完成了一个简单的使用 Bun 运行时和 TypeScript 编写的 WebSocket 天气预报服务。

还有一个英文的案例

Here’s an example of how to create a simple weather forecast WebSocket service using TypeScript and Bun runtime:

import { serve } from "bun";
 
// Simple in-memory storage for weather data
const weatherData = {
  "New York": { temperature: 25, condition: "Sunny" },
  "London": { temperature: 18, condition: "Cloudy" },
  "Tokyo": { temperature: 30, condition: "Rainy" },
};
 
serve({
  port: 3000,
  fetch(req, server) {
    // Upgrade the request to a WebSocket connection
    if (server.upgrade(req)) {
      return; // Do not return a Response
    }
    return new Response("Upgrade failed", { status: 500 });
  },
  websocket: {
    open(ws) {
      console.log("WebSocket connection opened");
    },
    message(ws, message) {
      const city = message.toString();
      if (city in weatherData) {
        const forecast = weatherData[city];
        ws.send(JSON.stringify({
          city,
          temperature: forecast.temperature,
          condition: forecast.condition,
        }));
      } else {
        ws.send(JSON.stringify({ error: "City not found" }));
      }
    },
    close(ws) {
      console.log("WebSocket connection closed");
    },
  },
});
 
console.log("WebSocket server running on port 3000");

To run this example:

  1. Save the code in a file named weather_server.ts
  2. Run it using Bun: bun run weather_server.ts

This example creates a simple WebSocket server that:

  1. Listens on port 3000
  2. Upgrades HTTP requests to WebSocket connections
  3. Handles incoming messages (city names) and responds with weather data
  4. Uses a simple in-memory object to store weather data for demonstration purposes

To test this server, you can use a WebSocket client or create a simple HTML page with JavaScript to connect to the WebSocket server:

<!DOCTYPE html>
<html>
<body>
<input id="cityInput" type="text" placeholder="Enter city name">
<button onclick="getWeather()">Get Weather</button>
<div id="result"></div>
 
<script>
const socket = new WebSocket('ws://localhost:3000');
 
socket.onopen = function(e) {
  console.log("Connection established");
};
 
socket.onmessage = function(event) {
  const data = JSON.parse(event.data);
  document.getElementById('result').innerHTML = `
    City: ${data.city}<br>
    Temperature: ${data.temperature}°C<br>
    Condition: ${data.condition}
  `;
};
 
function getWeather() {
  const city = document.getElementById('cityInput').value;
  socket.send(city);
}
</script>
</body>
</html>

This example demonstrates a basic WebSocket service for weather forecasts. In a real-world application, you would typically:

  1. Use a real weather API to fetch up-to-date data
  2. Implement proper error handling and connection management
  3. Add authentication and security measures
  4. Optimize for performance and scalability

Remember to handle WebSocket connections securely and consider implementing features like periodic updates or push notifications for changes in weather conditions.