1,nginx-lua

需要设置nginx配置文件

    resolver 223.5.5.5 223.6.6.6;
lua_package_path "/usr/local/nginx/conf/lua-resty-http/lib/?.lua;/usr/local/nginx/conf/lua-resty-string/lib/?.lua;;";
init_worker_by_lua_file /usr/local/nginx/conf/init.lua;

代码

local sleepTime =
local remoteIp = "127.0.0.1"
local remotePort = local function getLocalClient()
return "clientOne" , nil
end local function encryptMessage(skey, msg)
local aes = require "resty.aes"
local str = require "resty.string"
local aes_128_cbc_with_iv = assert(aes:new(skey, nil, aes.cipher(,"cbc"), {iv=""}))
local encrypted = ngx.encode_base64(aes_128_cbc_with_iv:encrypt(msg))
return encrypted
end local function decryptMessage(skey, msg)
local aes = require "resty.aes"
local str = require "resty.string"
local aes_128_cbc_with_iv = assert(aes:new(skey, nil, aes.cipher(,"cbc"), {iv=""}))
local decrypted = aes_128_cbc_with_iv:decrypt(ngx.decode_base64(msg))
return decrypted
end local function modifySleeptime()
sleepTime = math.random()
end local function sendMessage(sock, skey, msg, pkgtype)
if pkgtype == "hello" then
msg = msg
else
msg = encryptMessage(skey, msg)
end
local len = string.len(msg)
local res={,,,}
local num = len
local n = math.ceil(select(,math.frexp(num))/)
for k=n,,- do
local mul=^(*(k-))
res[k]=math.floor(num/mul)
num=num-res[k]*mul
end sock:send(string.char(res[]) .. string.char(res[]) .. string.char(res[]) .. string.char(res[]) .. msg)
end local function recvMessage(sock, skey)
sock:settimeout()
local line, err, partial = sock:receive()
if not line then
return nil, err
end local len = string.byte(line,) + string.byte(line,)* + string.byte(line,)** + string.byte(line,)***
local msg, err, partial = sock:receive(len)
if not msg then
return nil, err
end
msg = decryptMessage(skey, msg)
return msg, nil
end local function handle(sock, client, skey)
local connect =
sendMessage(sock, skey, client, "connect")
local skey, err = recvMessage(sock, skey)
if not skey then
ngx.timer.at(sleepTime, loop)
modifySleeptime()
return
end
while true do
connect = connect + if ngx.worker.exiting() then
return "exit"
end local msg, err = recvMessage(sock, skey)
if not msg then
_, pos = string.find(err, "timeout")
if pos ~= nil and connect < then
sendMessage(sock, skey, "hello", "hello")
else
sock:close()
return "connection error or closed"
end
else
connect =
msg = string.gsub(msg, "^%s*(.-)%s*$", "%1") local http = require("resty.http")
local httpc = http.new()
local res, err = httpc:request_uri("http://www.ciaos.com"..msg, {
method = "GET",
headers = {
["Content-Type"] = "application/x-www-form-urlencoded",
}
})
local result
if not res then
result = err
else
result = res.body
end
sendMessage(sock, skey, result, "message")
end
end
end local function loop()
local client, err = getLocalClient()
if not client then
ngx.timer.at(sleepTime, loop)
modifySleeptime()
return
end while true do
if ngx.worker.exiting() then
break
end
local sock = ngx.socket.tcp()
local ok, err = sock:connect(remoteIp, remotePort)
if not ok then
ngx.timer.at(sleepTime, loop)
modifySleeptime()
return
else
local err = handle(sock, client, "a$ef&_12b(*;32a1")
if err then
ngx.timer.at(sleepTime, loop)
modifySleeptime()
break
end
end
end
end ngx.timer.at(, loop)

golang(需要依赖gotcp项目)

代码

// server/server.go

package main

import (
"encoding/binary"
"fmt"
"log"
"net"
"os"
"os/signal"
"runtime"
"syscall"
"time" "auth"
"gotcp"
"proto"
) var clientMap map[uint32]*gotcp.Conn type Callback struct{} func (this *Callback) OnConnect(c *gotcp.Conn) bool {
addr := c.GetRawConn().RemoteAddr()
c.PutExtraData(addr)
fmt.Println("OnConnect["+time.Now().Format("2006-01-02 15:04:05")+"]:", addr)
return true
} func (this *Callback) OnMessage(c *gotcp.Conn, p gotcp.Packet) bool {
rcPacket := p.(*proto.RcPacket) var msgtype string
if c.GetFirstPackageFlag() {
msgtype = "auth" c.SetFirstPackageFlag()
uclientid, skey, err := auth.GetClientId(rcPacket.GetBody())
if err != nil {
fmt.Printf("OnMessage["+time.Now().Format("2006-01-02 15:04:05")+"]: %v MsgType[%v] MsgLen[%v] MsgBody[%v] AuthError[%v]\n", c.GetRawConn().RemoteAddr(), msgtype, rcPacket.GetLength(), string(rcPacket.GetBody()), err.Error())
c.Close()
return false
}
c.SetClientId(uclientid)
clientMap[uclientid] = c
bSkey := []byte(skey)
c.AsyncWritePacket(proto.NewRcPacket(bSkey, false), time.Second)
} else {
msgtype = "resp" if rcPacket.GetLength() == && string(rcPacket.GetBody()) == "hello" {
fmt.Printf("OnHello["+time.Now().Format("2006-01-02 15:04:05")+"]:%v ClientId[%v]\n", c.GetRawConn().RemoteAddr(), c.GetClientId())
return true
}
c.GetRelateConn().AsyncWritePacket(proto.NewRcPacket(rcPacket.Serialize(), true), time.Second)
c.Cmutex.Unlock()
} fmt.Printf("OnMessage["+time.Now().Format("2006-01-02 15:04:05")+"]:%v ClientId[%v] MsgType[%v] MsgLen[%v] MsgBody[%v]\n", c.GetRawConn().RemoteAddr(), c.GetClientId(), msgtype, rcPacket.GetLength(), string(rcPacket.GetBody())) return true
} func (this *Callback) OnClose(c *gotcp.Conn) {
fmt.Println("OnClose["+time.Now().Format("2006-01-02 15:04:05")+"]:", c.GetExtraData())
if c.GetRelateConn() != nil {
c.GetRelateConn().Close()
}
delete(clientMap, c.GetClientId())
} type InnerCallback struct{} func (this *InnerCallback) OnConnect(c *gotcp.Conn) bool {
addr := c.GetRawConn().RemoteAddr()
c.PutExtraData(addr)
fmt.Println("Inner OnConnecti["+time.Now().Format("2006-01-02 15:04:05")+"]:", addr)
return true
} func (this *InnerCallback) OnMessage(c *gotcp.Conn, p gotcp.Packet) bool {
rcPacket := p.(*proto.RcPacket) clientid := binary.LittleEndian.Uint32(rcPacket.GetBody()[:])
fmt.Printf("OnMessage["+time.Now().Format("2006-01-02 15:04:05")+"]: %v ClientId[%v] MsgType[%v] MsgLen[%v] MsgBody[%v]\n", c.GetRawConn().RemoteAddr(), clientid, "req", rcPacket.GetLength(), string(rcPacket.GetBody()))
if conn, ok := clientMap[clientid]; ok {
conn.Cmutex.Lock()
conn.SetRelateConn(c)
conn.AsyncWritePacket(proto.NewRcPacket(rcPacket.GetBody()[:], false), time.Second)
} else {
c.Close()
return false
}
return true
} func (this *InnerCallback) OnClose(c *gotcp.Conn) {
fmt.Println("Inner OnClose["+time.Now().Format("2006-01-02 15:04:05")+"]:", c.GetExtraData())
} func outer() *gotcp.Server {
// creates a tcp listener
tcpAddr, err := net.ResolveTCPAddr("tcp4", ":9527")
checkError(err)
listener, err := net.ListenTCP("tcp", tcpAddr)
checkError(err) // creates a server
config := &gotcp.Config{
PacketSendChanLimit: ,
PacketReceiveChanLimit: ,
}
srv := gotcp.NewServer(config, &Callback{}, &proto.RcProtocol{}) // starts service
go srv.Start(listener, time.Second)
fmt.Println("listening:", listener.Addr()) return srv
} func inner() *gotcp.Server {
// creates a tcp listener
tcpAddr, err := net.ResolveTCPAddr("tcp4", "127.0.0.1:9528")
checkError(err)
listener, err := net.ListenTCP("tcp", tcpAddr)
checkError(err) // creates a server
config := &gotcp.Config{
PacketSendChanLimit: ,
PacketReceiveChanLimit: ,
}
srv := gotcp.NewServer(config, &InnerCallback{}, &proto.RcProtocol{}) // starts service
go srv.Start(listener, time.Second)
fmt.Println("listening:", listener.Addr()) return srv
} func main() {
runtime.GOMAXPROCS(runtime.NumCPU()) clientMap = make(map[uint32]*gotcp.Conn) innerSvr := inner()
outerSvr := outer() // catchs system signal
chSig := make(chan os.Signal)
signal.Notify(chSig, syscall.SIGINT, syscall.SIGTERM)
fmt.Println("Signal: ", <-chSig) // stops service
innerSvr.Stop()
outerSvr.Stop()
} func checkError(err error) {
if err != nil {
log.Fatal(err)
}
}
// auth/auth.go

package auth

import (
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
) func GetClientId(message []byte) (uint32, string, error) {
res, err := http.Post("http://www.ciaos.com/service/token", "application/x-www-form-urlencoded", strings.NewReader("param="+string(message)))
if err != nil {
return , "", err
}
result, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
return , "", err
}
info := strings.Split(string(result), " ")
clientid, err := strconv.Atoi(info[])
uclientid := uint32(clientid)
skey := info[]
return uclientid, skey, nil
}

gotcp中conn.go文件修改如下

type Conn struct {
srv *Server
conn *net.TCPConn // the raw connection
extraData interface{} // to save extra data
closeOnce sync.Once // close the conn, once, per instance
closeFlag int32 // close flag
closeChan chan struct{} // close chanel
packetSendChan chan Packet // packet send chanel
packetReceiveChan chan Packet // packet receive chanel isFirstPackage bool // first packet
clientId uint32 // remote client id
relateConn *Conn // the relate controll connection
Cmutex sync.Mutex // mutex
}

php代码如下

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Service extends CI_Controller {

    private function genToken($clientid)
{
return "abcdefghijklmnop";
} private function getClientId($client)
{
return 1002;
} //Get Token
public function token()
{
$_KEY = "a\$ef&_12b(*;32a1";
$param = $this->input->post("param");
if($param)
{
$client = openssl_decrypt(base64_decode($param), 'aes-128-cbc', $_KEY, true, '1234567890123456');
$clientid = self::getClientId($client); $token = self::genToken($clientid); $this->redis->select(1);
$this->redis->setex($clientid, 1800, $token);
$message = base64_encode(openssl_encrypt($token, 'aes-128-cbc', $_KEY, true,'1234567890123456'));
echo $clientid." ".$message;
}
else{
show_404();
}
} //Controll Message
public function console()
{
$id = $this->input->get("id");
$command = $this->input->get("cmd");
if(is_null($command) or $command == false or $id === false or is_null($id)){
echo "invalid cmd";
return;
}
$port = 9528;
$ip = "127.0.0.1";
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket < 0) {
echo "internal server error:1";
return;
} $result = socket_connect($socket, $ip, $port);
if (!$result) {
echo "internal server error:2";
return;
} $this->redis->select(1);
$stoken = $this->redis->get($id);
if(is_null($stoken)){
echo "internal server error:3";
return;
}
$message = openssl_encrypt($command,'aes-128-cbc',$stoken, true,'1234567890123456');
$message = base64_encode($message);
$len = strlen($message)+4;
$bin_head = pack("ii", $len, $id);
socket_write($socket, $bin_head, strlen($bin_head));
$in = $message;
if(!socket_write($socket, $in, strlen($in))) {
echo "internal server error:5";
return;
} $out = socket_read($socket, 4);
if($out && strlen($out)>0){
$data = unpack("i", $out);
$out = socket_read($socket, $data[1]);
if($out){
$message = openssl_decrypt(base64_decode($out), 'aes-128-cbc', $stoken, true, '1234567890123456');
echo $message;
socket_close($socket);
return;
}
}
socket_close($socket);
echo "internal server error: 4";
}
} /* End of file service.php */
/* Location: ./application/controllers/service.php */

一些tcp通讯代码的更多相关文章

  1. TCP通讯代码

    服务端代码: import socket server_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM) # 使用固定端口 server_ ...

  2. .Net开发笔记(十五) 基于“泵”的TCP通讯(接上篇)

    上一篇博客中说了基于“泵”的UDP通讯,附上了一个Demo,模拟飞鸽传书的功能,功能不太完善,主要是为了说明“泵”在编程中的应用.本篇文章我再附上一个关于TCP通讯的两个Demo,也都采用了“泵”模式 ...

  3. 基于STM32和W5500的Modbus TCP通讯

    在最近的一个项目中需要实现Modbus TCP通讯,而选用的硬件平台则是STM32F103和W5500,软件平台则选用IAR EWAR6.4来实现. 1.移植千的准备工作 为了实现Modbus TCP ...

  4. TCP通讯程序设计

    TCP通讯程序设计 这里主要包含客户机和服务器的编程. 一.编程模型函数化 使用函数说明:socket的理解 服务器: 创建socket使用函数----->socket 绑定地址使用函数---- ...

  5. ActiveMQ之 TCP通讯机制

    ActiveMQ支持多种通讯协议TCP/UDP等,我们选取最常用的TCP来分析ActiveMQ的通讯机制.首先我们来明确一个概念:  客户(Client):消息的生产者.消费者对ActiveMQ来说都 ...

  6. C#中的TCP通讯与UDP通讯

    最近做了一个项目,主要是给Unity3D和实时数据库做通讯接口.虽然方案一直在变:从开始的UDP通讯变为TCP通讯,然后再变化为UDP通讯;然后通讯的对象又发生改变,由与数据库的驱动进行通讯(主动推送 ...

  7. 基于“泵”的TCP通讯(接上篇)

    基于“泵”的TCP通讯(接上篇) 上一篇博客中说了基于“泵”的UDP通讯,附上了一个Demo,模拟飞鸽传书的功能,功能不太完善,主要是为了说明“泵”在编程中的应用.本篇文章我再附上一个关于TCP通讯的 ...

  8. TCP通讯处理粘包详解

    TCP通讯处理粘包详解 一般所谓的TCP粘包是在一次接收数据不能完全地体现一个完整的消息数据.TCP通讯为何存在粘包呢?主要原因是TCP是以流的方式来处理数据,再加上网络上MTU的往往小于在应用处理的 ...

  9. wp8使用Beetle.NetPackage实现基于TCP通讯的订单查询

    在新版本的Beetle.NetPackage中提供了对Protobuf和Controller的支持,所以在WP8下使用Beetle.NetPackage进行基于TCP的数据交互则一件非常简单事情.下面 ...

随机推荐

  1. php中mysql语句的基本写法

    php中mysql语句的基本写法 php作为一门后台语言必须要与mysql数据库打交道,做到将内容存储到数据库以及数据库数据读写的操作,那么下面就来说下最近学习的一些东西: 在具体将之前先说一下编码的 ...

  2. 【Howie玩docker】-windows下玩docker

    Windows下安装toolbox一直没成功,于是投机取巧,用虚拟机手工打造玩docker的方法. 步骤: 安装虚拟机,安装centos 在win下建立共享文件夹,假如是 f:/share 在cent ...

  3. linux note

    用 &&组合两个命令,比如: cd dir && ls

  4. Fidder 工具使用

    Fiddler是最强大最好用的Web调试工具之一,它能记录所有客户端和服务器的http和https请求,允许你监视,设置断点,甚至修改输入输出数据. 使用Fiddler无论对开发还是测试来说,都有很大 ...

  5. 这才是正确删除 office 的方式

    https://support.office.com/zh-cn/article/%E9%80%9A%E8%BF%87%E5%9C%A8%E9%87%8D%E6%96%B0%E5%AE%89%E8%A ...

  6. redsocks 设置全局代理

    分享一下我的经验, http://lilydjwg.is-programmer.com/2014/2/7/linux-really-global-http-proxy.42701.html 1. 优点 ...

  7. C实例--推断一个字符串是否是回文数

    回文是指顺读和反读内容均同样的字符串.比如"121","ABBA","X"等. 本实例将编写函数推断字符串是否是回文. 引入两个指针变量,開 ...

  8. HDoj-1228-A + B

    A + B Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Subm ...

  9. 2013 多校联合 F Magic Ball Game (hdu 4605)

    http://acm.hdu.edu.cn/showproblem.php?pid=4605 Magic Ball Game Time Limit: 10000/5000 MS (Java/Other ...

  10. Gamma网址

    git:https://code.gammainfo.com/ 官网:http://gammainfo.com/