Table of Contents
回复讨论(解决方案)
Home Backend Development PHP Tutorial 接收socket数据,但是绑定服务器那边数据是一直发的,为什么只接受到一串

接收socket数据,但是绑定服务器那边数据是一直发的,为什么只接受到一串

Jun 23, 2016 pm 01:02 PM

发送数据是这样@,13,56,89,5,21,64,79,51,46,31,$的,我接收的是这样的
{"is_ok":1,"data":@,13,56,89,5,21,64,79,51,46,31,$}
但是数据是一直发,虽然都是同一串数据,但是我只接受一串,后面就没有了,怎么定义数据的开始和结束标志的!!想在服务端添加到数据库看看,但是怎么转成json数据格式啊!发送数据格式要怎么改,因为后面要用ajax得到数据添加到highchart,怎么调用这串数据啊!是写成json数组吗!
 

/*------------------------------------------------------ *///-- socket客户端/*------------------------------------------------------ */ //+error_reporting(0);set_time_limit(0); // 接收GET数据$msg = isset($_GET['msg']) ? trim($_GET['msg']) : ''; // socket错误代码function strerror($code) {    $str = '';    switch($code) {        case 10022:            $str = '参数错误';            break;        case 10048:            $str = '通常每个套接字地址(协议/网络地址/端口)只允许使用一次。';            break;        case 10061:            $str = '由于服务器积极拒绝,连接失败!';            break;        default:            $str = '未知错误';            break;    }    return $str;} function get_server_config() {    return simplexml_load_file('include/server_config.xml');}// 获取socket服务端配置信息$server_conf = get_server_config();$ip = $server_conf->ip;$port = (int)$server_conf->port; $out_str = '{"is_ok":0,"data":'; // 创建socketif(($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {    $out_str .= '"' . strerror(socket_last_error()) . '"}';} // 连接到服务器else if(socket_connect($socket, $ip, $port) === false) {    $out_str .= '"' . strerror(socket_last_error($socket)) . '"}';} // 向服务器发送请求else if(socket_write($socket, $msg, strlen($msg)) === false) {    $out_str .= '"' . strerror(socket_last_error($socket)) . '"}';} else if(($out = socket_read($socket, 8192)) === false) {    $out_str .= '"' . strerror(socket_last_error($socket)) . '"}';} else {    $out_str = '{"is_ok":1,"data":' . $out . '}';} echo $out_str; // 关闭socketsocket_close($socket); /*------------------------------------------------------ *///-- socket服务端/*------------------------------------------------------ */ include('include/init.php');// 设置时区//date_default_timezone_set('Etc/GMT-8'); echo str_repeat(' ', 4000);error_reporting(0);set_time_limit(0); ob_start(); // 显示提示信息function show_tip($msg, $is_ok=true) {    if($is_ok) {        $msg = '<font color=\"#090\">' . $msg . '</font>';    } else {        $msg = '<font color=\"#f00\">' . $msg . '</font>';    }    echo '<script>parent.$("#tip").showTip("' . date('Y-m-d H:i:s', time()) . '","' . $msg . '");</script>';    ob_flush();    flush();    sleep(1);} // 获取socket服务端配置信息$server_conf = get_server_config();$ip = $server_conf->ip;$port = (int)$server_conf->port;$server_name = $server_conf->name; show_tip($server_name . ' 正在初始化...'); // 创建socketif(($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {    show_tip($server_name . ' 创建失败,原因:' . strerror(socket_last_error()), false);} else {    show_tip($server_name . ' 创建成功!');} // 绑定socket到指定IP,端口if(socket_bind($socket, $ip, $port) === false) {       show_tip('绑定 ' . $server_name . ' 失败,原因:' . strerror(socket_last_error($socket)), false);} else {    show_tip('绑定 ' . $server_name . ' 到 ' . $ip . ', ' . $port);} // 监听if(socket_listen($socket, 5) === false) {    show_tip($server_name . ' 监听失败,原因:' . strerror(socket_last_error($socket)), false);} else {    show_tip($server_name . ' 正在监听中...');    echo '<script>location.href="login.php";</script>';    ob_flush();    flush();} static $w_socket = null;    // webstatic $a_socket = null;    // android $rNodeDataModel = new NodeDataModel(); do {    if(($msg_socket = socket_accept($socket)) === false) {        socket_close($msg_socket);        break;    } else {        if(($buffer = socket_read($msg_socket, 8192)) !== false) {             $buffer = trim($buffer);             if($buffer == 'web') {                $w_socket = $msg_socket;            } else if($buffer == 'android') {                $a_socket = $msg_socket;            } else if($buffer != 'stop') {                 $str_arr = explode('&', $buffer);                if(!empty($str_arr[1])) {                     $c_name = trim($str_arr[0]); // 客户端标识                    $c_data = trim($str_arr[1]); // 客户端数据                    if($c_name == 'computer') {                        // 判断数据是否为json格式                        if(($r_arr = json_decode($c_data, true)) != null) {                             if($w_socket != null) {                                socket_write($w_socket, $c_data, strlen($c_data));                            }                            if($a_socket != null) {                                socket_write($a_socket, $c_data, strlen($c_data));                            }                             // 添加到数据库                            foreach($r_arr as $v) {                                $v['node_id'] = $v['point'];                                unset($v['point']);                                $v['create_time'] = time();                                $rNodeDataModel->insert($v);                            }                        }                    }                 }                 socket_close($msg_socket);             } else {                socket_close($msg_socket);            }        } else {            socket_close($msg_socket);        }    } } while($buffer != 'stop'); // 关闭socketsocket_close($w_socket);socket_close($a_socket);socket_close($socket);
Copy after login


回复讨论(解决方案)

你请求一次,自然只得到一次数据

你请求一次,自然只得到一次数据

哪请问版主,怎么多次请求,还有时间间隔怎么写的,用不用定义那串数据的开始和结束标记啊!谢谢版主

你请求一次,自然只得到一次数据

如果要把那串数据添加到数据库,那串数据要怎么修改格式(原始格式或者接收到的)和调用,

你多次调用客户端程序,就可多次收到数据了
如何把数据放进数据库,取决于你数据库中是如何保存的
传输的数据格式应按你的使用需求进行设计

你多次调用客户端程序,就可多次收到数据了
如何把数据放进数据库,取决于你数据库中是如何保存的
传输的数据格式应按你的使用需求进行设计


function connect() {		$.ajax({			url: 'client.php?msg=web',			type: 'get',			dataType: 'json',			success: function(result) {//由服务器返回,并根据 dataType 参数进行处理后的数据;描述状态的字符串。				  $('#tb tr:gt(0)').remove();//删除之前的数据				if(result.is_ok) {					var x = (new Date()).getTime();					$.each(result.data, function(i) {						var index = parseInt(result.data[i].point) - 1;						chart01.series[index].addPoint([x, parseFloat(result.data[i])], true, true);						chart02.series[index].addPoint([x, parseFloat(result.data[i])], true, true);						chart03.series[index].addPoint([x, parseFloat(result.data[i])], true, true);						chart04.series[index].addPoint([x, parseFloat(result.data[i])], true, true);						chart05.series[index].addPoint([x, parseFloat(result.data[i])], true, true);						chart06.series[index].addPoint([x, parseFloat(result.data[i])], true, true);						chart07.series[index].addPoint([x, parseFloat(result.data[i])], true, true);						chart08.series[index].addPoint([x, parseFloat(result.data[i])], true, true);						chart09.series[index].addPoint([x, parseFloat(result.data[i])], true, true);						chart10.series[index].addPoint([x, parseFloat(result.data[i])], true, true);					},1000);//这里的是隔时间自动取数据				} else {					error = true;					layer.alert(result.data);				}	        },			complete: function(XHR, TS) {//请求完成后回调函数 (请求成功或失败之后均调用)。				XHR = null; // 释放XMLHttprequest对象				if(!error)					connect();			}		});	}	function create_data() {		var data = [],			time = (new Date()).getTime(),			i;		for (i = -19; i <= 0; i++) {			data.push({				x: time + i * 1000			});		}		return data;	}	var chart01, chart02, chart03, chart04, chart05, chart06, chart07,chart08,chart09,chart10;	function create_chart(id, t, y_t) {		var chart = new Highcharts.Chart({			chart: {				renderTo: id,				type: 'spline',				animation: Highcharts.svg,				backgroundColor: '#272735',				events: {					load: connect				}			},			title: {				text: t			},			xAxis: {				type: 'datetime',				tickPixelInterval: 150			},			yAxis: {				title: {					text: y_t				},				plotLines: [{//线					value: 0,					width: 1,					color: '#808080'				}]			},			tooltip: {				formatter: function() {					return '<b>'+ this.series.name +'</b><br/>'+					Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x);				}			},			series: [{				name: '实时数据',				data: [29.9, -71.5, 106.4, 15.2, 144.0, 258.0, 135.6, 177.5, 216.4, 194.1, 95.6, 54.4] //create_data()			}],			credits:{				 enabled:false			}		});		return chart;	}
Copy after login
如何把取到的data数据赋给每个chart表,{"is_ok":1,"data":[13,56,89,5,21,64,79,51,46,31]},如何在series中的data表示出来。希望给一些实质的建议。谢谢

建议你认真阅读一下 Highcharts 的 ajax 范例
肯定要比我专业的多

就是把data的值,怎么拿出来不知道,像result.data[i]这种形式

  你代码请求一次当然是一个结果

  你代码请求一次当然是一个结果

我把网站打开,只打开一次啊!不停刷新才不断请求啊。所以加了这个  
$.each(result.data, function(i) {
                        var index = parseInt(result.data[i].point) - 1;
 
                        chart01.series[index].addPoint([x, parseFloat(result.data[i])], true, true);
                        chart02.series[index].addPoint([x, parseFloat(result.data[i])], true, true);
                        chart03.series[index].addPoint([x, parseFloat(result.data[i])], true, true);
                        chart04.series[index].addPoint([x, parseFloat(result.data[i])], true, true);
                        chart05.series[index].addPoint([x, parseFloat(result.data[i])], true, true);
                        chart06.series[index].addPoint([x, parseFloat(result.data[i])], true, true);
                        chart07.series[index].addPoint([x, parseFloat(result.data[i])], true, true);
                        chart08.series[index].addPoint([x, parseFloat(result.data[i])], true, true);
                        chart09.series[index].addPoint([x, parseFloat(result.data[i])], true, true);
                        chart10.series[index].addPoint([x, parseFloat(result.data[i])], true, true);
                    },1000);//1000每隔时间会自动取数据
关键怎么data的值怎么给坐标  chart1.series[index].addPoint([x, parseFloat(result.data[i])], true, true);
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles