您的位置:首页 > 其它

一个socket发送调试信息的类

2014-03-04 19:24 309 查看
using UnityEngine;
using System.Collections;
using System;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;

public class sockectLogger : MonoBehaviour {
public static ArrayList outStr = new ArrayList();
public static string inStr = "";
public static TcpClient client = null;
public static NetworkStream stream = null;

// Use this for initialization
void Start () {
SocketConnection("192.168.0.97", 1234);
}

// Update is called once per frame
void Update () {

}
public static void doLog(string str){
outStr.Add(str);
}
private void SocketConnection (string LocalIP, int LocalPort)
{
client = new TcpClient ();
try {
IPAddress ip = IPAddress.Parse (LocalIP);
IPEndPoint ipe = new IPEndPoint (ip, LocalPort);

client.Connect (ipe);
Thread socketThread = new Thread (socketWork);
socketThread.Start ();
} catch (SocketException e) {
//ErrLog.RecordErr(e, ModuleName, "AsySocket", "");
log (e.ToString ());
} catch (Exception e) {
log ("ReceiveInt e=" + e.ToString ());
}
log ("=*> Socket thread start!");
}
public static void log (string str)
{
Debug.Log (str);
}
public static void socketWork ()
{
log ("=*> socketWork started v 5.0");
while (!client.Connected) {
log (".");
Thread.Sleep (300);
}

Thread.Sleep (500);//
log ("=*> socketWork connected");
stream = client.GetStream ();
string tmp;
while (true) {
try {
if(outStr.Count>0){
tmp = outStr[0].ToString();
outStr.RemoveAt(0);
log (tmp);
Send (tmp);
inStr = ReceiveString();
log(inStr);
}
Thread.Sleep (10);
} catch (SocketException e) {
log ("socket thread exception 0:" + e.ToString ());
break;
} catch (Exception e) {
log ("socket thread exception 1:" + e.ToString ());
break;
}
}
log ("Socket thread end");
}
public static void Send (string data)
{
try {
byte[] _data = System.Text.Encoding.Default.GetBytes(data);
int len = _data.Length;
log ("Send -->*> " + data.Length + "/" + len);
stream.Write (_data, 0, data.Length);//,data.getPos(),SocketFlags.ControlDataTruncated);
} catch (SocketException e) {
log ("Send e=" + e.ToString ());
} catch (Exception e) {
log ("Send e=" + e.ToString ());
}
}
public static string ReceiveString ()
{
try {
byte[] recvBytes = new byte[512];
stream.Read (recvBytes, 0, 512);//从服务器端接受返回信息
//log ("receivestring recvBytes="+recvBytes.ToString());
string data = Encoding.UTF8.GetString (recvBytes);
return data;
} catch (SocketException e) {
log ("ReceiveString e=" + e.ToString ());
} catch (Exception e) {
log ("ReceiveString e=" + e.ToString ());
}
return "";
}
}


接受信息的服务器端:

<?php
ignore_user_abort(true);
set_time_limit(0);
ini_set('display_errors',true);
ini_set('session.use_cookies',false);
error_reporting(E_ALL);
$addr = "0.0.0.0";
$port = @ (int)$argv[1];
if($port<1024) $port = 1234;
define('EC',chr(1));
define('PORT',$port);

$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);

if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
echo 'Unable to set option on socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
}

if($socket < 0) {
echo "Socket create:".$socket_strerror($socket)."\n";
exit;
}

if (! ($ret = socket_bind($socket, $addr, $port)) ) {
$cmd =isset($_SERVER['WINDIR'])? "netstat -an -o | find \"".$port."\"":"netstat -anp | grep \"".$port."\"";
$output = NULL;
exec( $cmd, $output , $return_var);
echo "
-----------------------------------------------
$cmd
<pre>";
var_dump($output, $return_var);
echo "/<pre>";
//echo "//AS!\n";
exit;
}

if ( ($ret = socket_listen($socket, 5)) < 0 ) {
echo "socket listen:".socket_strerror()."\n";
exit;
}

socket_set_nonblock($socket);
echo "Wainting for a connection at $port:\n";
$totalBytesRecv = 0;
$clients = array($socket);
while(true) {
$read = $clients;
$writes=NULL;$execs=NULL;
if(socket_select($read, $writes, $execs, 2) < 1){
echo ".";
continue;
}

if(in_array($socket,$read)) {
$newsock = socket_accept($socket);
socket_set_nonblock($newsock);
socket_getpeername($newsock,$remoteIP,$remotePort);
$userSN = $remoteIP.'_'.$remotePort;
$clients[$userSN] = $newsock;

$key = array_search($socket,$read);
unset($read[$key]);
echo $remoteIP.":".$remotePort." conected in.\r\n";
}

foreach($read as $read_sock) {
$data = @socket_read($read_sock, 2048, PHP_BINARY_READ);
$data = trim($data);
if(strlen($data) == 2048){
socket_close($read_sock);
continue;
}
@socket_getpeername($read_sock, $remoteIP, $remotePort);
$userSN = $remoteIP.'_'.$remotePort;

if($data == false) {
$key = array_search($read_sock, $clients);
unset($clients[$key]);
continue;
}
echo "\n".date("H:i:s").'->'.$data."\n";
$totalBytesRecv += strlen($data);
socket_write($read_sock,"OK".chr(0));
}
}
socket_close($socket);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐