尤川豪   ·  1年前
445 貼文  ·  275 留言

支援 FP 的語言寫起 socket 好像比 OOP 好得多了

C language

用土炮的 C 語言來寫 可以直接用上 linux socket 全部 API 深入認識底層功能

但 code 就很難讀 如果是要寫應用程式 這也太冗長

https://github.com/davidleitw/socket

PHP language- OOP

如果用高階程式語言 比方說 PHP 然後用 OOP 的寫法

http://socketo.me/docs/hello-world

<?php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class Chat implements MessageComponentInterface {
    public function onOpen(ConnectionInterface $conn) {
    }

    public function onMessage(ConnectionInterface $from, $msg) {
    }

    public function onClose(ConnectionInterface $conn) {
    }

    public function onError(ConnectionInterface $conn, \Exception $e) {
    }
}

是簡單一些 但 socket programming 就很不適合這樣 OOP 的寫法

JavaScript - FP

如果是支援 FP 的語言 比方說 js

寫起來簡單多了

https://socket.io/docs/v4/

import { Server } from "socket.io";

const io = new Server(3000);

io.on("connection", (socket) => {
  // send a message to the client
  socket.emit("hello from server", 1, "2", { 3: Buffer.from([4]) });

  // receive a message from the client
  socket.on("hello from client", (...args) => {
    // ...
  });
});

More comparisons

再舉例,以操作 unix domain socket 來說

python https://stackoverflow.com/questions/42263167/read-and-write-from-unix-socket-connection-with-python

#!/usr/bin/python

import socket
import os, os.path
import time
from collections import deque

if os.path.exists("/tmp/socket_test.s"):
  os.remove("/tmp/socket_test.s")

server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
server.bind("/tmp/socket_test.s")
while True:
  server.listen(1)
  conn, addr = server.accept()
  datagram = conn.recv(1024)
  if datagram:
    tokens = datagram.strip().split()
    if tokens[0].lower() == "post":
      flist.append(tokens[1])
      conn.send(len(tokens) + "")
    elif tokens[0].lower() == "get":
      conn.send(tokens.popleft())
    else:
      conn.send("-1")
    conn.close()

javascript https://stackoverflow.com/questions/27783579/unix-sockets-on-nodejs

'use strict';

const net = require('net');
const unixSocketServer = net.createServer();

unixSocketServer.listen('/tmp/unixSocket', () => {
  console.log('now listening');
});

unixSocketServer.on('connection', (s) => {
  console.log('got connection!');
  s.write('hello world');
  s.end();
});

可以看到 python 是比較接近 linux 真正的 C 實作,也就是用無窮迴圈來待命

而 javascript 就是用比較 declarative 的方式描述,行為也就是 function 直接當參數傳進去


對 front-end developer 來說

因為 UI 一定是 non-blocking 所以開發者很習慣 on sometime -> do something 這種 非同步執行的寫法

這種感覺剛好會跟 socketing programming 類似 on sometime -> do something

這程度的抽象化 比 OOP、procedural programming 好上太多

web 出身的開發者 就選 nodejs 來寫吧 哈哈

  分享   共 669 次點閱
共有 0 則留言
還沒有人留言。歡迎分享您的觀點、或是疑問。
您的留言
尤川豪
445 貼文  ·  275 留言

Devs.tw 是讓工程師寫筆記、網誌的平台。隨手紀錄、寫作,方便日後搜尋!

歡迎您一起加入寫作與分享的行列!

查看所有文章