《初識TCP》iOS、macOS實現socket client與socket server
第一種方式,使用基於Cocoa的第三方框架CocoaAsyncSocket
不需要升級握手協議,使用起來異常的簡單,如上圖,實現了基於TCP的socket客戶端與服務端,點選下載demo
第二種方式,需要升級握手協議的的WebSocket,可以參考facebook的開源框架SocketRocket
這次改用php指令碼建立socket服務端,程式碼如下:
<?php
error_reporting(E_ALL);
ob_implicit_flush();
$sk=new Sock('127.0.0.1',8000);
$sk->run();
class Sock{
public $sockets;
public $users;
public $master;
public function __construct($address, $port){
$this->master=$this->WebSocket($address, $port);
$this->sockets=array('s'=>$this->master);
}
function run(){
while(true){
$changes=$this->sockets;
$write=NULL;
$except=NULL;
socket_select($changes,$write,$except,NULL);
foreach($changes as $sock){
if($sock==$this->master){
$client=socket_accept($this->master);
//$key=uniqid();
$this->sockets[]=$client;
$this->users[]=array(
'socket'=>$client,
'shou'=>false
);
}else{
$len=socket_recv($sock,$buffer,2048,0);
$k=$this->search($sock);
if($len<7){
echo "close";
$name=$this->users[$k]['ming'];
$this->close($sock);
$this->send2($name,$k);
continue;
}
if(!$this->users[$k]['shou']){
$this->woshou($k,$buffer);
}else{
$buffer = $this->uncode($buffer);
$this->send($k,$buffer);
}
}
}
}
}
function close($sock){
$k=array_search($sock, $this->sockets);
socket_close($sock);
unset($this->sockets[$k]);
unset($this->users[$k]);
$this->e("key:$k close");
}
function search($sock){
foreach ($this->users as $k=>$v){
if($sock==$v['socket'])
return $k;
}
return false;
}
function WebSocket($address,$port){
$server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($server, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($server, $address, $port);
socket_listen($server);
$this->e('Server Started : '.date('Y-m-d H:i:s'));
$this->e('Listening on : '.$address.' port '.$port);
return $server;
}
function woshou($k,$buffer){
$buf = substr($buffer,strpos($buffer,'Sec-WebSocket-Key:')+18);
$key = trim(substr($buf,0,strpos($buf,"\r\n")));
$new_key = base64_encode(sha1($key."258EAFA5-E914-47DA-95CA-C5AB0DC85B11",true));
$new_message = "HTTP/1.1 101 Switching Protocols\r\n";
$new_message .= "Upgrade: websocket\r\n";
$new_message .= "Sec-WebSocket-Version: 13\r\n";
$new_message .= "Connection: Upgrade\r\n";
$new_message .= "Sec-WebSocket-Accept: " . $new_key . "\r\n\r\n";
socket_write($this->users[$k]['socket'],$new_message,strlen($new_message));
$this->users[$k]['shou']=true;
return true;
}
function uncode($str){
$mask = array();
$data = '';
$msg = unpack('H*',$str);
$head = substr($msg[1],0,2);
if (hexdec($head{1}) === 8) {
$data = false;
}else if (hexdec($head{1}) === 1){
$mask[] = hexdec(substr($msg[1],4,2));
$mask[] = hexdec(substr($msg[1],6,2));
$mask[] = hexdec(substr($msg[1],8,2));
$mask[] = hexdec(substr($msg[1],10,2));
$s = 12;
$e = strlen($msg[1])-2;
$n = 0;
for ($i=$s; $i<= $e; $i+= 2) {
$data .= chr($mask[$n%4]^hexdec(substr($msg[1],$i,2)));
$n++;
}
}
return $data;
}
function code($msg){
$msg = preg_replace(array('/\r$/','/\n$/','/\r\n$/',), '', $msg);
$frame = array();
$frame[0] = '81';
$len = strlen($msg);
$frame[1] = $len<16?'0'.dechex($len):dechex($len);
$frame[2] = $this->ord_hex($msg);
$data = implode('',$frame);
return pack("H*", $data);
}
function ord_hex($data) {
$msg = '';
$l = strlen($data);
for ($i= 0; $i<$l; $i++) {
$msg .= dechex(ord($data{$i}));
}
return $msg;
}
function send($k,$msg){
$this->send1($k,$this->code($msg),'all');
// parse_str($msg,$g);
// $this->e($msg);
// $ar=array();
// if($g['type']=='add'){
// $this->users[$k]['ming']=$g['ming'];
// $ar['add']=true;
// $ar['nrong']='歡迎'.$g['ming'].'加入!';
// $ar['users']=$this->getusers();
// $key='all';
// }else if($g['type']=='ltiao'){
// $ar['nrong']=$g['nr'];
// $key=$g['key'];
// }
// $msg=json_encode($ar);
// $this->e($msg);
// $msg = $this->code($msg);
// // $this->send1($k,$msg,$key);
// $this->send1($k,$this->code($msg),$key);
// socket_write($this->users[$k]['socket'],$msg,strlen($msg));
}
function getusers(){
$ar=array();
foreach($this->users as $k=>$v){
$ar[$k]=$v['ming'];
}
return $ar;
}
function send1($k,$str,$key='all'){
if($key=='all'){
foreach($this->users as $v){
socket_write($v['socket'],$str,strlen($str));
}
}else{
if($k!=$key)
socket_write($this->users[$k]['socket'],$str,strlen($str));
socket_write($this->users[$key]['socket'],$str,strlen($str));
}
}
function send2($ming,$k){
$ar['remove']=true;
$ar['removekey']=$k;
$ar['nrong']=$ming.'退出聊天室';
$str = $this->code(json_encode($ar));
$this->send1(false,$str,'all');
}
function e($str){
$path=dirname(__FILE__).'/log.txt';
$str=$str."\n";
error_log($str,3,$path);
echo iconv('utf-8','gbk//IGNORE',$str);
}
}
?>
電腦安裝php執行環境後,在終端輸入:php 檔案路徑
即可執行php指令碼
執行結果如下:
Server Started : 2018-05-07 06:29:43
Listening on : 127.0.0.1 port 8000
下載iOS客戶端程式碼,(要在模擬器操作)執行即可連線通訊。
相關文章
- HTTP、Socket與TCPHTTPTCP
- socket.io client + socketio-netty server簡析clientNettyServer
- socket與TCP/IP區別TCP
- 從Linux原始碼看Socket(TCP)Client端的ConnectLinux原始碼TCPclient
- TCP socket和web socket的區別TCPWeb
- TCP/IP 和SocketTCP
- 通過 Socket 實現 TCP 程式設計入門TCP程式設計
- socket,TCP/IP的理解TCP
- .NET TCP、UDP、Socket、WebSocketTCPUDPWeb
- [iOS] Socket & CocoaAsyncSocket介紹與使用iOS
- Python使用socket_TCP實現小檔案下載PythonTCP
- C語言透過socket實現TCP客戶端C語言TCP客戶端
- Linux Socket C語言網路程式設計:TCP SocketLinuxC語言程式設計TCP
- telnet連線socket serverServer
- Netty實現Web SocketNettyWeb
- Tomcat實現Web SocketTomcatWeb
- socket程式設計實現tcp伺服器_C/C++程式設計TCP伺服器C++
- epoll+socket實現 socket併發 linux伺服器Linux伺服器
- Spring Boot實現Web SocketSpring BootWeb
- socket實現聊天功能(二)
- TCP/IP、HTTP和Socket總結TCPHTTP
- day30:TCP&UDP:socketTCPUDP
- Linux學習/TCP Socket通訊LinuxTCP
- server端雙socket 設計方式Server
- Socket和TCP連線過程解析TCP
- python-20-優化socket_tcpPython優化TCP
- Hyperf-Socket.io實現私聊
- 從linux原始碼看socket(tcp)的timeoutLinux原始碼TCP
- 從Linux原始碼看Socket(TCP)的bindLinux原始碼TCP
- 手把手教你 Socket 通訊(TCP/IP)TCP
- 從Linux原始碼看Socket(TCP)的acceptLinux原始碼TCP
- http、socket、tcp的區別和聯絡?HTTPTCP
- node.js 用socket實現聊天Node.js
- UNIX Domain Socket實現簡易聊天AI
- socket實現簡單ssh服務
- 初識TcpTCP
- Java:基於TCP協議網路socket程式設計(實現C/S通訊)JavaTCP協議程式設計
- java多執行緒實現TCP網路Socket程式設計(C/S通訊)Java執行緒TCP程式設計