swoole Tcp Server的服务端,js怎么连接服务?


$server = new Swoole\Server('0.0.0.0', 9501);

$server->on('start', function ($server) {
    echo "TCP Server is started at tcp://127.0.0.1:9501\n";
});

$server->on('connect', function ($server, $fd) {
//    echo "connection open: {$fd}\n";
});

$server->on('receive', function ($server, $fd, $reactor_id, $data) {
    echo "{$data}\n";
    $server->send($fd, "Swoole: {$data}");
});

$server->on('close', function ($server, $fd) {
//    echo "connection close: {$fd}\n";
});

$server->start();

服务端用上面的代码,js怎么连接服务?

阅读 1.9k
1 个回答

如果你是期待使用浏览器端的 JavaScript 去连接,那 Swoole 方面你应该使用 WebSocket 服务,而不是 TCP。

参考:WebSockets - Web API 接口参考 | MDN

如果是 TCP + Node 环境下的,可以使用 Net 库,可参考 Node.js Tutorial => A simple TCP client

const Net = require('net');

// 配置目标
const port = 8080;
const host = 'localhost';


const client = new Net.Socket();
// 发起连接
client.connect({ port: port, host: host }), function() {
    // 连接成功、并发送信息
    client.write('Hello, server.');
});

// 收到消息
client.on('data', function(chunk) {
    console.log(`Data received from the server: ${chunk.toString()}.`);
    
    // 断开连接
    client.end();
});

client.on('end', function() {
    // 连接断开事件
    console.log('Requested an end to the TCP connection');
});

注:如果是希望在 Node 使用 WebSocket,推荐 websockets/ws

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题