websocket 簡易聊天

2021-07-29 19:38:56 字數 3653 閱讀 9717

//通過命令列執行php檔案 如 php -q index.php

// php -s localhost:8000 瀏覽器訪問index.html

chatdemotitle>

charset="utf-8">

name="viewport"

content="width=device-width,initial-scale=1, maximum-scale=1, user-scalable=no">

href=""

rel="stylesheet">

type="text/css">

--html, body

body

.container

.title

.content

.content

.show-area

.content

.show-area

.message

.content

.write-area

.content

.write-area

.send

.content

.write-area

#name

-->

style>

head>

class="container">

class="title">簡易聊天demodiv>

class="content">

class="show-area">

div>

class="write-area">

class="btn btn-default send" >傳送button>

div>

name="name"

id="name"

type="text"

placeholder="input your name">

div>

name="message"

id="message"

cols="38"

rows="4"

placeholder="input your message...">

textarea>

div>

div>

div>

div>

src="">

script>

src="">

script>

$(function

() //收到訊息

websocket.onmessage = function

(event)

if(type == 'system')

$('#message').val('');

window.location.hash = '#'+i;

}//發生錯誤

websocket.onerror = function

(event)

//連線關閉

websocket.onclose = function

(event)

function

send

() if(!message)

var msg = ;

try catch(ex)

}//按下enter鍵傳送訊息

$(window).keydown(function

(event)

});//點傳送按鈕傳送訊息

$('.send').bind('click',function

());

}else

});

script>

body>

html>

//服務端 index.php

<?php

$host = '127.0.0.1';

$port = '9505';

$null = null;

//建立tcp socket

$socket = socket_create(af_inet, sock_stream, sol_tcp);

socket_set_option($socket, sol_socket, so_reuseaddr, 1);

socket_bind($socket, 0, $port);

//監聽埠

socket_listen($socket);

//連線的client socket 列表

$clients = array($socket);

//設定乙個死迴圈,用來監聽連線 ,狀態

while (true)

//輪詢 每個client socket 連線

foreach ($changed

as$changed_socket)

//檢查offline的client

$buf = @socket_read($changed_socket, 1024, php_normal_read);

if ($buf === false)

}}// 關閉監聽的socket

socket_close($sock);

//傳送訊息的方法

function

send_message

($msg)

return

true;

}//解碼資料

function

unmask

($text)

elseif($length == 127)

else

$text = "";

for ($i = 0; $i

< strlen($data); ++$i)

return

$text;

}//編碼資料

function

mask

($text)

//握手的邏輯

websocket簡單實現聊天

1.多人聊天 from geventwebsocket.handler import websockethandler 請求處理wsgi http from geventwebsocket.server import wsgiserver 替換flask原來的wsgi服務 from geventwe...

golang 簡易聊天

client.go package main import net fmt bufio echo codec time var quitsemaphore chan bool func main 傳送訊息 func sendmessage conn net.tcpconn lk b byte msg...

WebSocket 和 Golang 實現聊天功能

這個示例應用程式展示了如何使用 websocket,golang 和 jquery 建立乙個簡單的web聊天應用程式。這個示例的源 在 這個示例需要 golang 開發環境。該頁面描述如何安裝開發環境。go get gary.burd.info go websocket chat go websoc...