diff --git a/README.md b/README.md index 63bab48..e8b6675 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # cocosocket -cocosocket是一个为cocos2d-x手机网络游戏准备的底层通信框架,满足网络游戏客户端 +cocosocket是一个为cocos2d-x和unity 3D手机网络游戏准备的底层通信框架,满足网络游戏客户端 对于高性能网络通信的需求,适用于基于socket的手机网游。 ## 问题 @@ -77,6 +77,13 @@ server 了理解这两者的难度,你可以从server端或client端入手,这将非常有助于理解另一端 。 +##关于cocosocket4unity + +这个程序是为unity 3D准备的,api和c++版本的客户端很像,实现的是相同的功能,适用 +于unity 3D网游。里面我嵌入了litjson的代码用并修复了它的一个bug:utf8字符串乱码 +,如果你刚好需要json解析,那么建议使用,否则请删去litjson的代码即可。 + + ## 结语 ok,那么我想你现在应该对cocosocket有个大概了解了。enjoy it. diff --git a/cocosocket-client/AutoLock.h b/cocosocket-client/AutoLock.h index 3381cf4..f0feef0 100644 --- a/cocosocket-client/AutoLock.h +++ b/cocosocket-client/AutoLock.h @@ -1,4 +1,4 @@ -锘#ifndef AUTOMUTEX_H +#ifndef AUTOMUTEX_H #define AUTOMUTEX_H #include "Mutext.h" diff --git a/cocosocket-client/BlockingQueue.h b/cocosocket-client/BlockingQueue.h index a891655..2354b60 100644 --- a/cocosocket-client/BlockingQueue.h +++ b/cocosocket-client/BlockingQueue.h @@ -1,4 +1,4 @@ -锘/* +/* * File: BlockingQueue.h * Author: beykery * diff --git a/cocosocket-client/ByteBuf.cpp b/cocosocket-client/ByteBuf.cpp index 38524d6..060ac39 100644 --- a/cocosocket-client/ByteBuf.cpp +++ b/cocosocket-client/ByteBuf.cpp @@ -1,4 +1,4 @@ -锘/* +/* * File: ByteBuf.cpp * Author: beykery * @@ -10,7 +10,8 @@ #include #include #include "ByteBuf.h" -#include "iconv.h" +#include +//#include "iconv.h" #include "cocos2d.h" ByteBuf::ByteBuf(int len) { @@ -510,7 +511,7 @@ char* ByteBuf::GetRaw() return this->data; } - +/** int ByteBuf::Convert(std::string& str, const char* to, const char* from) { #if(CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) @@ -558,4 +559,5 @@ int ByteBuf::Convert(std::string& str, const char* to, const char* from) #if(CC_TARGET_PLATFORM == CC_PLATFORM_IOS) return 0; #endif -} \ No newline at end of file +} +**/ \ No newline at end of file diff --git a/cocosocket-client/ByteBuf.h b/cocosocket-client/ByteBuf.h index 633edac..071cd9f 100644 --- a/cocosocket-client/ByteBuf.h +++ b/cocosocket-client/ByteBuf.h @@ -1,4 +1,4 @@ -锘/* +/* * File: ByteBuf.h * Author: beykery * @@ -67,7 +67,7 @@ public: ByteBuf* WriteUTF8(char* value); const ByteBuf* Copy(); char* GetRaw(); - static int ByteBuf::Convert(std::string& str, const char* to, const char* from); + //static int ByteBuf::Convert(std::string& str, const char* to, const char* from); private: char* data; //鏁版嵁 int len; //闀垮害锛屽彲鎵╁睍闀垮害 diff --git a/cocosocket-client/DefaultListerner.cpp b/cocosocket-client/DefaultListerner.cpp index 720fabf..c1f02cb 100644 --- a/cocosocket-client/DefaultListerner.cpp +++ b/cocosocket-client/DefaultListerner.cpp @@ -1,4 +1,4 @@ -锘/* +/* * File: DefaultListerner.cpp * Author: beykery * @@ -12,7 +12,7 @@ #include "Socket.h" #include "ByteBuf.h" #include "Frame.h" -#include "iconv.h" +//#include "iconv.h" #include "cocos2d.h" using namespace std; @@ -26,17 +26,17 @@ DefaultListerner::~DefaultListerner() void DefaultListerner::OnClose(Socket* so, bool fromRemote) { - CCLOG("%s\n","closed"); + printf("%s\n","closed"); } void DefaultListerner::OnError(Socket* so, const char* e) { - CCLOG("%s\n","error connection"); + printf("%s\n","error connection"); } void DefaultListerner::OnIdle(Socket* so) { - CCLOG("%s\n","connection idle"); + printf("%s\n","connection idle"); } /** @@ -54,7 +54,7 @@ void DefaultListerner::OnMessage(Socket* so, ByteBuf* frame) // wchar_t* u2 = frame->ReadUTF8(); float c = frame->ReadFloat(); std::string ss=frame->ReadUTF8(); - CCLOG("%s\n",ss.c_str()); + printf("%s\n",ss.c_str()); delete frame; // Frame* s = new Frame(r); // s->PutInt(c); @@ -68,11 +68,11 @@ void DefaultListerner::OnMessage(Socket* so, ByteBuf* frame) void DefaultListerner::OnOpen(Socket* so) { - CCLOG("%s","connecting"); + printf("%s","connecting"); Frame* f=new Frame(512); f->PutFloat(10.1f); std::string buff="鎴戝幓鍟奱銆傘傘傘傘"; - ByteBuf::Convert(buff,"utf-8","gbk"); + //ByteBuf::Convert(buff,"utf-8","gbk"); f->PutString((char*)buff.c_str()); //f->PutString(s); f->End(); diff --git a/cocosocket-client/DefaultListerner.h b/cocosocket-client/DefaultListerner.h index 5ad4f9e..2f80c40 100644 --- a/cocosocket-client/DefaultListerner.h +++ b/cocosocket-client/DefaultListerner.h @@ -1,4 +1,4 @@ -锘/* +/* * File: DefaultListerner.h * Author: beykery * diff --git a/cocosocket-client/Frame.cpp b/cocosocket-client/Frame.cpp index 78934b1..a4c8a00 100644 --- a/cocosocket-client/Frame.cpp +++ b/cocosocket-client/Frame.cpp @@ -1,4 +1,4 @@ -锘/* +/* * File: Frame.cpp * Author: beykery * diff --git a/cocosocket-client/Frame.h b/cocosocket-client/Frame.h index f91d372..227e832 100644 --- a/cocosocket-client/Frame.h +++ b/cocosocket-client/Frame.h @@ -1,4 +1,4 @@ -锘/* +/* * File: Frame.h * Author: beykery * diff --git a/cocosocket-client/LVProtocal.cpp b/cocosocket-client/LVProtocal.cpp index c21d20f..3d73ffe 100644 --- a/cocosocket-client/LVProtocal.cpp +++ b/cocosocket-client/LVProtocal.cpp @@ -1,4 +1,4 @@ -锘/* +/* * File: LVProtocal.cpp * Author: beykery * @@ -12,7 +12,6 @@ LVProtocal::LVProtocal() { this->status = 0; - frame = NULL; } diff --git a/cocosocket-client/LVProtocal.h b/cocosocket-client/LVProtocal.h index f95e4ab..29c84cd 100644 --- a/cocosocket-client/LVProtocal.h +++ b/cocosocket-client/LVProtocal.h @@ -1,4 +1,4 @@ -锘/* +/* * File: LVProtocal.h * Author: beykery * diff --git a/cocosocket-client/Mutext.cpp b/cocosocket-client/Mutext.cpp index af1156a..9c9ede1 100644 --- a/cocosocket-client/Mutext.cpp +++ b/cocosocket-client/Mutext.cpp @@ -1,4 +1,4 @@ -锘#include "Mutext.h" +#include "Mutext.h" Mutext::Mutext(int nShared, int nType) { diff --git a/cocosocket-client/Mutext.h b/cocosocket-client/Mutext.h index a4f2057..7c484a3 100644 --- a/cocosocket-client/Mutext.h +++ b/cocosocket-client/Mutext.h @@ -1,10 +1,10 @@ -锘#ifndef MUTEX_H +#ifndef MUTEX_H #define MUTEX_H #include class Mutext { private: - pthread_mutex_t mutext; + std::mutex mutext; public: Mutext(int sh = PTHREAD_PROCESS_PRIVATE, int type = PTHREAD_MUTEX_NORMAL); ~Mutext(); diff --git a/cocosocket-client/Protocal.h b/cocosocket-client/Protocal.h index 862164b..df14bc7 100644 --- a/cocosocket-client/Protocal.h +++ b/cocosocket-client/Protocal.h @@ -1,4 +1,4 @@ -锘/* +/* * File: Protocal.h * Author: beykery * diff --git a/cocosocket-client/Queue.h b/cocosocket-client/Queue.h index 4575e25..a9c2eb3 100644 --- a/cocosocket-client/Queue.h +++ b/cocosocket-client/Queue.h @@ -1,4 +1,4 @@ -锘/* +/* * File: Queue.h * Author: beykery * diff --git a/cocosocket-client/Socket.cpp b/cocosocket-client/Socket.cpp index 9576c34..a3c01c4 100644 --- a/cocosocket-client/Socket.cpp +++ b/cocosocket-client/Socket.cpp @@ -1,4 +1,4 @@ -锘/* +/* * File: Socket.cpp * Author: beykery * diff --git a/cocosocket-client/Socket.h b/cocosocket-client/Socket.h index b680507..927e18c 100644 --- a/cocosocket-client/Socket.h +++ b/cocosocket-client/Socket.h @@ -1,4 +1,4 @@ -锘/* +/* * File: Socket.h * Author: beykery * diff --git a/cocosocket-client/SocketListerner.cpp b/cocosocket-client/SocketListerner.cpp index f93fcb2..9b2f4a0 100644 --- a/cocosocket-client/SocketListerner.cpp +++ b/cocosocket-client/SocketListerner.cpp @@ -1,4 +1,4 @@ -锘/* +/* * File: SocketListerner.cpp * Author: beykery * diff --git a/cocosocket-client/SocketListerner.h b/cocosocket-client/SocketListerner.h index 967733e..ed18d5d 100644 --- a/cocosocket-client/SocketListerner.h +++ b/cocosocket-client/SocketListerner.h @@ -1,4 +1,4 @@ -锘/* +/* * File: SocketListerner.h * Author: beykery * diff --git a/cocosocket-client/Thread.cpp b/cocosocket-client/Thread.cpp index 3d26222..d0cdac4 100644 --- a/cocosocket-client/Thread.cpp +++ b/cocosocket-client/Thread.cpp @@ -1,4 +1,4 @@ -锘#include "Thread.h" +#include "Thread.h" #include "cocos2d.h" #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS #include diff --git a/cocosocket-client/Thread.h b/cocosocket-client/Thread.h index afd8a34..7c3f3e5 100644 --- a/cocosocket-client/Thread.h +++ b/cocosocket-client/Thread.h @@ -1,4 +1,4 @@ -锘#ifndef THREAD_H +#ifndef THREAD_H #define THREAD_H #include #include diff --git a/cocosocket-client/ThreadPool.cpp b/cocosocket-client/ThreadPool.cpp index 5623a10..f9a8d56 100644 --- a/cocosocket-client/ThreadPool.cpp +++ b/cocosocket-client/ThreadPool.cpp @@ -1,4 +1,4 @@ -锘#include +#include #include "ThreadPool.h" #include "Thread.h" #include diff --git a/cocosocket-client/ThreadPool.h b/cocosocket-client/ThreadPool.h index 6e2ce19..7fd3517 100644 --- a/cocosocket-client/ThreadPool.h +++ b/cocosocket-client/ThreadPool.h @@ -1,4 +1,4 @@ -锘#ifndef THREADPOOL_H +#ifndef THREADPOOL_H #define THREADPOOL_H #include diff --git a/cocosocket-client/WorkThread.cpp b/cocosocket-client/WorkThread.cpp index 583b353..0fb5388 100644 --- a/cocosocket-client/WorkThread.cpp +++ b/cocosocket-client/WorkThread.cpp @@ -1,4 +1,4 @@ -锘#include "WorkThread.h" +#include "WorkThread.h" #include "errno.h" #include "BlockingQueue.h" #include "Thread.h" diff --git a/cocosocket-client/WorkThread.h b/cocosocket-client/WorkThread.h index 23f8729..e8f51ab 100644 --- a/cocosocket-client/WorkThread.h +++ b/cocosocket-client/WorkThread.h @@ -1,4 +1,4 @@ -锘#ifndef WORKTHREAD_H +#ifndef WORKTHREAD_H #define WORKTHREAD_H #include diff --git a/cocosocket-client/build/Debug/Cygwin_4.x-Windows/ByteBuf.o b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/ByteBuf.o new file mode 100644 index 0000000..701b739 Binary files /dev/null and b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/ByteBuf.o differ diff --git a/cocosocket-client/build/Debug/Cygwin_4.x-Windows/ByteBuf.o.d b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/ByteBuf.o.d new file mode 100644 index 0000000..729e2d5 --- /dev/null +++ b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/ByteBuf.o.d @@ -0,0 +1,5 @@ +build/Debug/Cygwin_4.x-Windows/ByteBuf.o: ByteBuf.cpp ByteBuf.h cocos2d.h + +ByteBuf.h: + +cocos2d.h: diff --git a/cocosocket-client/build/Debug/Cygwin_4.x-Windows/DefaultListerner.o b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/DefaultListerner.o new file mode 100644 index 0000000..7b403b9 Binary files /dev/null and b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/DefaultListerner.o differ diff --git a/cocosocket-client/build/Debug/Cygwin_4.x-Windows/DefaultListerner.o.d b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/DefaultListerner.o.d new file mode 100644 index 0000000..cccaadf --- /dev/null +++ b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/DefaultListerner.o.d @@ -0,0 +1,19 @@ +build/Debug/Cygwin_4.x-Windows/DefaultListerner.o: DefaultListerner.cpp \ + DefaultListerner.h ByteBuf.h SocketListerner.h Socket.h Protocal.h \ + Thread.h Frame.h cocos2d.h + +DefaultListerner.h: + +ByteBuf.h: + +SocketListerner.h: + +Socket.h: + +Protocal.h: + +Thread.h: + +Frame.h: + +cocos2d.h: diff --git a/cocosocket-client/build/Debug/Cygwin_4.x-Windows/Frame.o b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/Frame.o new file mode 100644 index 0000000..c93134d Binary files /dev/null and b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/Frame.o differ diff --git a/cocosocket-client/build/Debug/Cygwin_4.x-Windows/Frame.o.d b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/Frame.o.d new file mode 100644 index 0000000..c8049a0 --- /dev/null +++ b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/Frame.o.d @@ -0,0 +1,10 @@ +build/Debug/Cygwin_4.x-Windows/Frame.o: Frame.cpp Frame.h ByteBuf.h \ + AutoLock.h Mutext.h + +Frame.h: + +ByteBuf.h: + +AutoLock.h: + +Mutext.h: diff --git a/cocosocket-client/build/Debug/Cygwin_4.x-Windows/LVProtocal.o b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/LVProtocal.o new file mode 100644 index 0000000..43901a7 Binary files /dev/null and b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/LVProtocal.o differ diff --git a/cocosocket-client/build/Debug/Cygwin_4.x-Windows/LVProtocal.o.d b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/LVProtocal.o.d new file mode 100644 index 0000000..4e8ba6c --- /dev/null +++ b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/LVProtocal.o.d @@ -0,0 +1,8 @@ +build/Debug/Cygwin_4.x-Windows/LVProtocal.o: LVProtocal.cpp LVProtocal.h \ + Protocal.h ByteBuf.h + +LVProtocal.h: + +Protocal.h: + +ByteBuf.h: diff --git a/cocosocket-client/build/Debug/Cygwin_4.x-Windows/Mutext.o b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/Mutext.o new file mode 100644 index 0000000..c3db281 Binary files /dev/null and b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/Mutext.o differ diff --git a/cocosocket-client/build/Debug/Cygwin_4.x-Windows/Mutext.o.d b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/Mutext.o.d new file mode 100644 index 0000000..8ce5e59 --- /dev/null +++ b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/Mutext.o.d @@ -0,0 +1,3 @@ +build/Debug/Cygwin_4.x-Windows/Mutext.o: Mutext.cpp Mutext.h + +Mutext.h: diff --git a/cocosocket-client/build/Debug/Cygwin_4.x-Windows/Socket.o b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/Socket.o new file mode 100644 index 0000000..6a85be5 Binary files /dev/null and b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/Socket.o differ diff --git a/cocosocket-client/build/Debug/Cygwin_4.x-Windows/Socket.o.d b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/Socket.o.d new file mode 100644 index 0000000..6469be0 --- /dev/null +++ b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/Socket.o.d @@ -0,0 +1,16 @@ +build/Debug/Cygwin_4.x-Windows/Socket.o: Socket.cpp cocos2d.h Socket.h \ + SocketListerner.h Protocal.h ByteBuf.h Thread.h Frame.h + +cocos2d.h: + +Socket.h: + +SocketListerner.h: + +Protocal.h: + +ByteBuf.h: + +Thread.h: + +Frame.h: diff --git a/cocosocket-client/build/Debug/Cygwin_4.x-Windows/SocketListerner.o b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/SocketListerner.o new file mode 100644 index 0000000..ab55e27 Binary files /dev/null and b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/SocketListerner.o differ diff --git a/cocosocket-client/build/Debug/Cygwin_4.x-Windows/SocketListerner.o.d b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/SocketListerner.o.d new file mode 100644 index 0000000..dd056c3 --- /dev/null +++ b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/SocketListerner.o.d @@ -0,0 +1,17 @@ +build/Debug/Cygwin_4.x-Windows/SocketListerner.o: SocketListerner.cpp \ + SocketListerner.h Socket.h Protocal.h ByteBuf.h Thread.h Frame.h \ + cocos2d.h + +SocketListerner.h: + +Socket.h: + +Protocal.h: + +ByteBuf.h: + +Thread.h: + +Frame.h: + +cocos2d.h: diff --git a/cocosocket-client/build/Debug/Cygwin_4.x-Windows/Thread.o b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/Thread.o new file mode 100644 index 0000000..43198c5 Binary files /dev/null and b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/Thread.o differ diff --git a/cocosocket-client/build/Debug/Cygwin_4.x-Windows/Thread.o.d b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/Thread.o.d new file mode 100644 index 0000000..999a24e --- /dev/null +++ b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/Thread.o.d @@ -0,0 +1,5 @@ +build/Debug/Cygwin_4.x-Windows/Thread.o: Thread.cpp Thread.h cocos2d.h + +Thread.h: + +cocos2d.h: diff --git a/cocosocket-client/build/Debug/Cygwin_4.x-Windows/ThreadPool.o b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/ThreadPool.o new file mode 100644 index 0000000..ebee704 Binary files /dev/null and b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/ThreadPool.o differ diff --git a/cocosocket-client/build/Debug/Cygwin_4.x-Windows/ThreadPool.o.d b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/ThreadPool.o.d new file mode 100644 index 0000000..8a80fe2 --- /dev/null +++ b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/ThreadPool.o.d @@ -0,0 +1,12 @@ +build/Debug/Cygwin_4.x-Windows/ThreadPool.o: ThreadPool.cpp ThreadPool.h \ + WorkThread.h Thread.h Queue.h Mutext.h + +ThreadPool.h: + +WorkThread.h: + +Thread.h: + +Queue.h: + +Mutext.h: diff --git a/cocosocket-client/build/Debug/Cygwin_4.x-Windows/WorkThread.o b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/WorkThread.o new file mode 100644 index 0000000..6c38371 Binary files /dev/null and b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/WorkThread.o differ diff --git a/cocosocket-client/build/Debug/Cygwin_4.x-Windows/WorkThread.o.d b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/WorkThread.o.d new file mode 100644 index 0000000..7cbd5d8 --- /dev/null +++ b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/WorkThread.o.d @@ -0,0 +1,16 @@ +build/Debug/Cygwin_4.x-Windows/WorkThread.o: WorkThread.cpp WorkThread.h \ + Thread.h Queue.h BlockingQueue.h Mutext.h AutoLock.h LinkedQueue.h + +WorkThread.h: + +Thread.h: + +Queue.h: + +BlockingQueue.h: + +Mutext.h: + +AutoLock.h: + +LinkedQueue.h: diff --git a/cocosocket-client/build/Debug/Cygwin_4.x-Windows/main.o b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/main.o new file mode 100644 index 0000000..9947d0a Binary files /dev/null and b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/main.o differ diff --git a/cocosocket-client/build/Debug/Cygwin_4.x-Windows/main.o.d b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/main.o.d new file mode 100644 index 0000000..96bfa64 --- /dev/null +++ b/cocosocket-client/build/Debug/Cygwin_4.x-Windows/main.o.d @@ -0,0 +1,27 @@ +build/Debug/Cygwin_4.x-Windows/main.o: main.cpp ThreadPool.h WorkThread.h \ + Thread.h Queue.h Mutext.h Socket.h SocketListerner.h Protocal.h \ + ByteBuf.h Frame.h DefaultListerner.h LVProtocal.h + +ThreadPool.h: + +WorkThread.h: + +Thread.h: + +Queue.h: + +Mutext.h: + +Socket.h: + +SocketListerner.h: + +Protocal.h: + +ByteBuf.h: + +Frame.h: + +DefaultListerner.h: + +LVProtocal.h: diff --git a/cocosocket-client/cocos2d.h b/cocosocket-client/cocos2d.h new file mode 100644 index 0000000..0e37c0e --- /dev/null +++ b/cocosocket-client/cocos2d.h @@ -0,0 +1,32 @@ +/* + * File: cocos2d.h + * Author: Beykery + * + * Created on 2014骞8鏈5鏃, 涓嬪崍3:23 + */ + +#ifndef COCOS2D_H +#define COCOS2D_H +// define supported target platform macro which CC uses. +#define CC_PLATFORM_UNKNOWN 0 +#define CC_PLATFORM_IOS 1 +#define CC_PLATFORM_ANDROID 2 +#define CC_PLATFORM_WIN32 3 +#define CC_PLATFORM_MARMALADE 4 +#define CC_PLATFORM_LINUX 5 +#define CC_PLATFORM_BADA 6 +#define CC_PLATFORM_BLACKBERRY 7 +#define CC_PLATFORM_MAC 8 +#define CC_PLATFORM_NACL 9 +#define CC_PLATFORM_EMSCRIPTEN 10 +#define CC_PLATFORM_TIZEN 11 +#define CC_PLATFORM_QT5 12 +#define CC_PLATFORM_WP8 13 +#define CC_PLATFORM_WINRT 14 + +// Determine target platform by compile environment macro. +#define CC_TARGET_PLATFORM CC_PLATFORM_UNKNOWN + + +#endif /* COCOS2D_H */ + diff --git a/cocosocket-client/dist/Debug/Cygwin_4.x-Windows/cocosocket-client.exe b/cocosocket-client/dist/Debug/Cygwin_4.x-Windows/cocosocket-client.exe new file mode 100644 index 0000000..a4bb620 Binary files /dev/null and b/cocosocket-client/dist/Debug/Cygwin_4.x-Windows/cocosocket-client.exe differ diff --git a/cocosocket-client/nbproject/Makefile-Debug.mk b/cocosocket-client/nbproject/Makefile-Debug.mk index e7c0f2e..73e22db 100644 --- a/cocosocket-client/nbproject/Makefile-Debug.mk +++ b/cocosocket-client/nbproject/Makefile-Debug.mk @@ -21,7 +21,7 @@ FC=gfortran AS=as # Macros -CND_PLATFORM=MinGW-Windows +CND_PLATFORM=Cygwin_4.x-Windows CND_DLIB_EXT=dll CND_CONF=Debug CND_DISTDIR=dist @@ -66,11 +66,11 @@ LDLIBSOPTIONS= # Build Targets .build-conf: ${BUILD_SUBPROJECTS} - "${MAKE}" -f nbproject/Makefile-${CND_CONF}.mk ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/cocosocket.exe + "${MAKE}" -f nbproject/Makefile-${CND_CONF}.mk ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/cocosocket-client.exe -${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/cocosocket.exe: ${OBJECTFILES} +${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/cocosocket-client.exe: ${OBJECTFILES} ${MKDIR} -p ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM} - ${LINK.cc} -o ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/cocosocket ${OBJECTFILES} ${LDLIBSOPTIONS} -lpthread + ${LINK.cc} -o ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/cocosocket-client ${OBJECTFILES} ${LDLIBSOPTIONS} -lpthread ${OBJECTDIR}/ByteBuf.o: ByteBuf.cpp ${MKDIR} -p ${OBJECTDIR} @@ -133,7 +133,7 @@ ${OBJECTDIR}/main.o: main.cpp # Clean Targets .clean-conf: ${CLEAN_SUBPROJECTS} ${RM} -r ${CND_BUILDDIR}/${CND_CONF} - ${RM} ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/cocosocket.exe + ${RM} ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/cocosocket-client.exe # Subprojects .clean-subprojects: diff --git a/cocosocket-client/nbproject/Makefile-Release.mk b/cocosocket-client/nbproject/Makefile-Release.mk index 8c90e69..27817aa 100644 --- a/cocosocket-client/nbproject/Makefile-Release.mk +++ b/cocosocket-client/nbproject/Makefile-Release.mk @@ -21,7 +21,7 @@ FC=gfortran AS=as # Macros -CND_PLATFORM=MinGW-Windows +CND_PLATFORM=Cygwin_4.x-Windows CND_DLIB_EXT=dll CND_CONF=Release CND_DISTDIR=dist @@ -66,11 +66,11 @@ LDLIBSOPTIONS= # Build Targets .build-conf: ${BUILD_SUBPROJECTS} - "${MAKE}" -f nbproject/Makefile-${CND_CONF}.mk ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/cocosocket.exe + "${MAKE}" -f nbproject/Makefile-${CND_CONF}.mk ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/cocosocket-client.exe -${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/cocosocket.exe: ${OBJECTFILES} +${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/cocosocket-client.exe: ${OBJECTFILES} ${MKDIR} -p ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM} - ${LINK.cc} -o ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/cocosocket ${OBJECTFILES} ${LDLIBSOPTIONS} + ${LINK.cc} -o ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/cocosocket-client ${OBJECTFILES} ${LDLIBSOPTIONS} ${OBJECTDIR}/ByteBuf.o: ByteBuf.cpp ${MKDIR} -p ${OBJECTDIR} @@ -133,7 +133,7 @@ ${OBJECTDIR}/main.o: main.cpp # Clean Targets .clean-conf: ${CLEAN_SUBPROJECTS} ${RM} -r ${CND_BUILDDIR}/${CND_CONF} - ${RM} ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/cocosocket.exe + ${RM} ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/cocosocket-client.exe # Subprojects .clean-subprojects: diff --git a/cocosocket-client/nbproject/Makefile-impl.mk b/cocosocket-client/nbproject/Makefile-impl.mk index 3bf3610..5287825 100644 --- a/cocosocket-client/nbproject/Makefile-impl.mk +++ b/cocosocket-client/nbproject/Makefile-impl.mk @@ -24,7 +24,7 @@ CLEAN_SUBPROJECTS=${CLEAN_SUBPROJECTS_${SUBPROJECTS}} # Project Name -PROJECTNAME=cocosocket +PROJECTNAME=cocosocket-client # Active Configuration DEFAULTCONF=Debug diff --git a/cocosocket-client/nbproject/Makefile-variables.mk b/cocosocket-client/nbproject/Makefile-variables.mk index e9aa03f..5b97946 100644 --- a/cocosocket-client/nbproject/Makefile-variables.mk +++ b/cocosocket-client/nbproject/Makefile-variables.mk @@ -7,21 +7,21 @@ CND_BASEDIR=`pwd` CND_BUILDDIR=build CND_DISTDIR=dist # Debug configuration -CND_PLATFORM_Debug=MinGW-Windows -CND_ARTIFACT_DIR_Debug=dist/Debug/MinGW-Windows -CND_ARTIFACT_NAME_Debug=cocosocket -CND_ARTIFACT_PATH_Debug=dist/Debug/MinGW-Windows/cocosocket -CND_PACKAGE_DIR_Debug=dist/Debug/MinGW-Windows/package -CND_PACKAGE_NAME_Debug=cocosocket.tar -CND_PACKAGE_PATH_Debug=dist/Debug/MinGW-Windows/package/cocosocket.tar +CND_PLATFORM_Debug=Cygwin_4.x-Windows +CND_ARTIFACT_DIR_Debug=dist/Debug/Cygwin_4.x-Windows +CND_ARTIFACT_NAME_Debug=cocosocket-client +CND_ARTIFACT_PATH_Debug=dist/Debug/Cygwin_4.x-Windows/cocosocket-client +CND_PACKAGE_DIR_Debug=dist/Debug/Cygwin_4.x-Windows/package +CND_PACKAGE_NAME_Debug=cocosocket-client.tar +CND_PACKAGE_PATH_Debug=dist/Debug/Cygwin_4.x-Windows/package/cocosocket-client.tar # Release configuration -CND_PLATFORM_Release=MinGW-Windows -CND_ARTIFACT_DIR_Release=dist/Release/MinGW-Windows -CND_ARTIFACT_NAME_Release=cocosocket -CND_ARTIFACT_PATH_Release=dist/Release/MinGW-Windows/cocosocket -CND_PACKAGE_DIR_Release=dist/Release/MinGW-Windows/package -CND_PACKAGE_NAME_Release=cocosocket.tar -CND_PACKAGE_PATH_Release=dist/Release/MinGW-Windows/package/cocosocket.tar +CND_PLATFORM_Release=Cygwin_4.x-Windows +CND_ARTIFACT_DIR_Release=dist/Release/Cygwin_4.x-Windows +CND_ARTIFACT_NAME_Release=cocosocket-client +CND_ARTIFACT_PATH_Release=dist/Release/Cygwin_4.x-Windows/cocosocket-client +CND_PACKAGE_DIR_Release=dist/Release/Cygwin_4.x-Windows/package +CND_PACKAGE_NAME_Release=cocosocket-client.tar +CND_PACKAGE_PATH_Release=dist/Release/Cygwin_4.x-Windows/package/cocosocket-client.tar # # include compiler specific variables # diff --git a/cocosocket-client/nbproject/Package-Debug.bash b/cocosocket-client/nbproject/Package-Debug.bash index 7855d6f..ea73db8 100644 --- a/cocosocket-client/nbproject/Package-Debug.bash +++ b/cocosocket-client/nbproject/Package-Debug.bash @@ -6,16 +6,16 @@ # Macros TOP=`pwd` -CND_PLATFORM=MinGW-Windows +CND_PLATFORM=Cygwin_4.x-Windows CND_CONF=Debug CND_DISTDIR=dist CND_BUILDDIR=build CND_DLIB_EXT=dll NBTMPDIR=${CND_BUILDDIR}/${CND_CONF}/${CND_PLATFORM}/tmp-packaging TMPDIRNAME=tmp-packaging -OUTPUT_PATH=${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/cocosocket -OUTPUT_BASENAME=cocosocket -PACKAGE_TOP_DIR=cocosocket/ +OUTPUT_PATH=${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/cocosocket-client +OUTPUT_BASENAME=cocosocket-client +PACKAGE_TOP_DIR=cocosocket-client/ # Functions function checkReturnCode @@ -60,15 +60,15 @@ mkdir -p ${NBTMPDIR} # Copy files and create directories and links cd "${TOP}" -makeDirectory "${NBTMPDIR}/cocosocket/bin" +makeDirectory "${NBTMPDIR}/cocosocket-client/bin" copyFileToTmpDir "${OUTPUT_PATH}.exe" "${NBTMPDIR}/${PACKAGE_TOP_DIR}bin/${OUTPUT_BASENAME}.exe" 0755 # Generate tar file cd "${TOP}" -rm -f ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package/cocosocket.tar +rm -f ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package/cocosocket-client.tar cd ${NBTMPDIR} -tar -vcf ../../../../${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package/cocosocket.tar * +tar -vcf ../../../../${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package/cocosocket-client.tar * checkReturnCode # Cleanup diff --git a/cocosocket-client/nbproject/Package-Release.bash b/cocosocket-client/nbproject/Package-Release.bash index c51ec71..10ddb43 100644 --- a/cocosocket-client/nbproject/Package-Release.bash +++ b/cocosocket-client/nbproject/Package-Release.bash @@ -6,16 +6,16 @@ # Macros TOP=`pwd` -CND_PLATFORM=MinGW-Windows +CND_PLATFORM=Cygwin_4.x-Windows CND_CONF=Release CND_DISTDIR=dist CND_BUILDDIR=build CND_DLIB_EXT=dll NBTMPDIR=${CND_BUILDDIR}/${CND_CONF}/${CND_PLATFORM}/tmp-packaging TMPDIRNAME=tmp-packaging -OUTPUT_PATH=${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/cocosocket -OUTPUT_BASENAME=cocosocket -PACKAGE_TOP_DIR=cocosocket/ +OUTPUT_PATH=${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/cocosocket-client +OUTPUT_BASENAME=cocosocket-client +PACKAGE_TOP_DIR=cocosocket-client/ # Functions function checkReturnCode @@ -60,15 +60,15 @@ mkdir -p ${NBTMPDIR} # Copy files and create directories and links cd "${TOP}" -makeDirectory "${NBTMPDIR}/cocosocket/bin" +makeDirectory "${NBTMPDIR}/cocosocket-client/bin" copyFileToTmpDir "${OUTPUT_PATH}.exe" "${NBTMPDIR}/${PACKAGE_TOP_DIR}bin/${OUTPUT_BASENAME}.exe" 0755 # Generate tar file cd "${TOP}" -rm -f ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package/cocosocket.tar +rm -f ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package/cocosocket-client.tar cd ${NBTMPDIR} -tar -vcf ../../../../${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package/cocosocket.tar * +tar -vcf ../../../../${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package/cocosocket-client.tar * checkReturnCode # Cleanup diff --git a/cocosocket-client/nbproject/configurations.xml b/cocosocket-client/nbproject/configurations.xml index 0d86721..ac309c3 100644 --- a/cocosocket-client/nbproject/configurations.xml +++ b/cocosocket-client/nbproject/configurations.xml @@ -1,7 +1,7 @@ - + - + main.cpp @@ -19,6 +19,7 @@ Thread.h ThreadPool.h WorkThread.h + cocos2d.h ByteBuf.cpp @@ -110,6 +111,8 @@ + + @@ -181,6 +184,8 @@ + + diff --git a/cocosocket-client/nbproject/private/configurations.xml b/cocosocket-client/nbproject/private/configurations.xml index d154678..6bf32f3 100644 --- a/cocosocket-client/nbproject/private/configurations.xml +++ b/cocosocket-client/nbproject/private/configurations.xml @@ -1,5 +1,5 @@ - + Makefile diff --git a/cocosocket-client/nbproject/private/private.xml b/cocosocket-client/nbproject/private/private.xml index aef7ea3..b3c9dd7 100644 --- a/cocosocket-client/nbproject/private/private.xml +++ b/cocosocket-client/nbproject/private/private.xml @@ -6,6 +6,11 @@ - + + file:/D:/projects/cocosocket/cocosocket-client/AutoLock.h + file:/D:/projects/cocosocket/cocosocket-client/Mutext.h + file:/D:/projects/cocosocket/cocosocket-client/BlockingQueue.h + file:/D:/projects/cocosocket/cocosocket-client/Mutext.cpp + diff --git a/cocosocket-server/src/org/ngame/socket/NSocket.java b/cocosocket-server/src/org/ngame/socket/NSocket.java index b8164ff..8ae56e0 100644 --- a/cocosocket-server/src/org/ngame/socket/NSocket.java +++ b/cocosocket-server/src/org/ngame/socket/NSocket.java @@ -9,453 +9,455 @@ import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.socket.SocketChannel; -import io.netty.handler.codec.http.DefaultFullHttpRequest; -import io.netty.handler.codec.http.DefaultFullHttpResponse; -import io.netty.handler.codec.http.HttpContent; -import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH; -import static io.netty.handler.codec.http.HttpHeaders.isKeepAlive; -import io.netty.handler.codec.http.HttpMethod; -import io.netty.handler.codec.http.HttpResponse; -import static io.netty.handler.codec.http.HttpResponseStatus.OK; -import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; +import io.netty.handler.codec.http.*; import io.netty.handler.timeout.IdleStateEvent; import io.netty.handler.timeout.IdleStateHandler; +import org.ngame.socket.framing.Framedata; +import org.ngame.socket.protocol.Protocol; + import java.net.InetSocketAddress; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; -import org.ngame.socket.framing.Framedata; -import org.ngame.socket.protocol.Protocol; + +import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH; +import static io.netty.handler.codec.http.HttpHeaders.isKeepAlive; +import static io.netty.handler.codec.http.HttpResponseStatus.OK; +import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; /** - * * @author beykery */ public final class NSocket extends ChannelInboundHandlerAdapter { - private static final Logger LOG = Logger.getLogger(NSocket.class.getName()); - private SocketListener listener; - private final SocketChannel channel; - private boolean closeReason;//鏄惁涓烘湇鍔″櫒涓诲姩鍏抽棴 - private final Protocol protocol; - private long sessionId; - private Map sessions; - private ChannelHandlerContext context; - private String closeReasonString;//鏂紑鍘熷洜鎻忚堪 - private boolean http;//閫氫俊鍗忚鏄惁涓篽ttp - private boolean keepAlive;//鏄惁keepalive - private boolean client;//鏄惁涓篽ttp瀹㈡埛绔 - private String uri;//鏈嶅姟鍣ㄥ湴鍧 + private static final Logger LOG = Logger.getLogger(NSocket.class.getName()); + private SocketListener listener; + private final SocketChannel channel; + private boolean closeReason;//鏄惁涓烘湇鍔″櫒涓诲姩鍏抽棴 + private final Protocol protocol; + private long sessionId; + private Map sessions; + private ChannelHandlerContext context; + private String closeReasonString;//鏂紑鍘熷洜鎻忚堪 + private boolean http;//閫氫俊鍗忚鏄惁涓篽ttp + private boolean keepAlive;//鏄惁keepalive + private boolean client;//鏄惁涓篽ttp瀹㈡埛绔 + private String uri;//鏈嶅姟鍣ㄥ湴鍧 - /** - * 杩炴帴 - * - * @param l - * @param ch - * @param protocol - */ - public NSocket(SocketListener l, SocketChannel ch, Protocol protocol) - { - channel = ch; - this.listener = l; - this.protocol = protocol; - } + /** + * 杩炴帴 + * + * @param l + * @param ch + * @param protocol + */ + public NSocket(SocketListener l, SocketChannel ch, Protocol protocol) + { + channel = ch; + this.listener = l; + this.protocol = protocol; + } - @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception - { - ByteBuf bb = null; - if (http)//濡傛灉鏄痟ttp鍗忚锛屽垯鍙栧嚭httprequest骞跺垎鏋 - { + public Protocol getProtocol() + { + return protocol; + } + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception + { + ByteBuf bb = null; + if (http)//濡傛灉鏄痟ttp鍗忚锛屽垯鍙栧嚭httprequest骞跺垎鏋 + { // if (msg instanceof DefaultHttpRequest) // { // System.out.println("binnnn"); // } else - if (msg instanceof DefaultFullHttpRequest)//server - { - DefaultFullHttpRequest req = (DefaultFullHttpRequest) msg; - this.keepAlive = isKeepAlive(req); - bb = req.content(); - } else if (msg instanceof HttpContent)//client - { - HttpContent response = (HttpContent) msg; - bb = response.content(); - } - } else - { - bb = (ByteBuf) msg; - } - if (bb != null) - { - try - { - ByteBuf fd = protocol.translateFrame(bb); - while (fd != null) - { - deliverMessage(fd); - fd = protocol.translateFrame(bb); - } - } finally - { - bb.release(); - } - } - } + if (msg instanceof DefaultFullHttpRequest)//server + { + DefaultFullHttpRequest req = (DefaultFullHttpRequest) msg; + this.keepAlive = isKeepAlive(req); + bb = req.content(); + } else if (msg instanceof HttpContent)//client + { + HttpContent response = (HttpContent) msg; + bb = response.content(); + } + } else + { + bb = (ByteBuf) msg; + } + if (bb != null) + { + try + { + ByteBuf fd = protocol.translateFrame(bb); + while (fd != null) + { + deliverMessage(fd); + fd = protocol.translateFrame(bb); + } + } finally + { + bb.release(); + } + } + } - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception - { - this.listener.onError(this, cause); - } + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception + { + this.listener.onError(this, cause); + } - @Override - public void channelActive(ChannelHandlerContext ctx) throws Exception - { - this.context = ctx; - this.listener.onOpen(this); - } + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception + { + this.context = ctx; + this.listener.onOpen(this); + } - @Override - public void channelInactive(ChannelHandlerContext ctx) throws Exception - { - this.listener.socketClosed(this, closeReason); - } + @Override + public void channelInactive(ChannelHandlerContext ctx) throws Exception + { + this.listener.socketClosed(this, closeReason); + } - @Override - public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception - { - if (evt instanceof IdleStateEvent) - { - IdleStateEvent event = (IdleStateEvent) evt; - this.listener.onIdle(this, event); - } - } + @Override + public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception + { + if (evt instanceof IdleStateEvent) + { + IdleStateEvent event = (IdleStateEvent) evt; + this.listener.onIdle(this, event); + } + } - /** - * 鏂紑杩炴帴 - * - * @return - */ - public ChannelFuture close() - { - this.closeReason = true; - return this.channel.close(); - } + /** + * 鏂紑杩炴帴 + * + * @return + */ + public ChannelFuture close() + { + this.closeReason = true; + return this.channel.close(); + } - /** - * 鏂紑杩炴帴 - * - * @param reason - * @return - */ - public ChannelFuture close(String reason) - { - this.closeReasonString = reason; - this.closeReason = true; - return this.channel.close(); - } + /** + * 鏂紑杩炴帴 + * + * @param reason + * @return + */ + public ChannelFuture close(String reason) + { + this.closeReasonString = reason; + this.closeReason = true; + return this.channel.close(); + } - /** - * 鍙戦佷竴甯э紙瀹屾暣鐨勪竴甯э級 - * - * @param data - * @return - */ - public ChannelFuture sendFrame(ByteBuf data) - { - if (http)//濡傛灉鏄痟ttp鍗忚锛屽垯鍙戦乺esponse - { - if (!client)//鏈嶅姟鍣ㄥ洖閫 - { - HttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, data); - res.headers().set(CONTENT_LENGTH, data.readableBytes()); - return this.context.writeAndFlush(res); - } else//瀹㈡埛绔殑request璇锋眰 - { - DefaultFullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, HttpMethod.POST, uri, data); - request.headers().set(CONTENT_LENGTH, data.readableBytes()); - return this.channel.writeAndFlush(request); - } - } else - { - return this.context.writeAndFlush(data); - } - } + /** + * 鍙戦佷竴甯э紙瀹屾暣鐨勪竴甯э級 + * + * @param data + * @return + */ + public ChannelFuture sendFrame(ByteBuf data) + { + if (http)//濡傛灉鏄痟ttp鍗忚锛屽垯鍙戦乺esponse + { + if (!client)//鏈嶅姟鍣ㄥ洖閫 + { + HttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, data); + res.headers().set(CONTENT_LENGTH, data.readableBytes()); + return this.context.writeAndFlush(res); + } else//瀹㈡埛绔殑request璇锋眰 + { + DefaultFullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, HttpMethod.POST, uri, data); + request.headers().set(CONTENT_LENGTH, data.readableBytes()); + return this.channel.writeAndFlush(request); + } + } else + { + return this.context.writeAndFlush(data); + } + } - /** - * 鍙戦佷竴甯 - * - * @param data - * @return - */ - public ChannelFuture sendFrame(Framedata data) - { - return this.sendFrame(data.getData()); - } + /** + * 鍙戦佷竴甯 + * + * @param data + * @return + */ + public ChannelFuture sendFrame(Framedata data) + { + return this.sendFrame(data.getData()); + } - private void deliverMessage(ByteBuf fd) - { - this.listener.onMessage(this, fd); - } + private void deliverMessage(ByteBuf fd) + { + this.listener.onMessage(this, fd); + } - public boolean isOpen() - { - return this.channel.isActive(); - } + public boolean isOpen() + { + return this.channel.isActive(); + } - public long getSessionId() - { - return sessionId; - } + public long getSessionId() + { + return sessionId; + } - public void setSessionId(long sessionId) - { - this.sessionId = sessionId; - } + public void setSessionId(long sessionId) + { + this.sessionId = sessionId; + } - /** - * 鑾峰彇session鍊 - * - * @param key - * @return - */ - public Object getSession(String key) - { - return sessions == null ? null : sessions.get(key); - } + /** + * 鑾峰彇session鍊 + * + * @param key + * @return + */ + public Object getSession(String key) + { + return sessions == null ? null : sessions.get(key); + } - /** - * 鑾峰彇session鍊 - * - * @param key - * @param def - * @return - */ - public Object getSession(String key, Object def) - { - Object r = sessions == null ? null : sessions.get(key); - return r == null ? def : r; - } + /** + * 鑾峰彇session鍊 + * + * @param key + * @param def + * @return + */ + public Object getSession(String key, Object def) + { + Object r = sessions == null ? null : sessions.get(key); + return r == null ? def : r; + } - /** - * 鍒犻櫎 - * - * @param key - * @return - */ - public Object removeSession(String key) - { - return sessions == null ? null : sessions.remove(key); - } + /** + * 鍒犻櫎 + * + * @param key + * @return + */ + public Object removeSession(String key) + { + return sessions == null ? null : sessions.remove(key); + } - /** - * 娓呯┖session鏁版嵁 - */ - public void clearSession() - { - sessions = null; - } + /** + * 娓呯┖session鏁版嵁 + */ + public void clearSession() + { + sessions = null; + } - /** - * 璁剧疆session鍊 - * - * @param key - * @param value - */ - public void setSession(String key, Object value) - { - if (sessions == null) - { - sessions = new HashMap<>(); - } - sessions.put(key, value); - } + /** + * 璁剧疆session鍊 + * + * @param key + * @param value + */ + public void setSession(String key, Object value) + { + if (sessions == null) + { + sessions = new HashMap<>(); + } + sessions.put(key, value); + } - /** - * 鑾峰彇鎵鏈夌殑session閿 - * - * @return - */ - public Set getSessionKeys() - { - return sessions == null ? null : sessions.keySet(); - } + /** + * 鑾峰彇鎵鏈夌殑session閿 + * + * @return + */ + public Set getSessionKeys() + { + return sessions == null ? null : sessions.keySet(); + } - @Override - public String toString() - { - InetSocketAddress local = channel.localAddress(); - InetSocketAddress remote = channel.remoteAddress(); - return local.getAddress().getHostAddress() + ":" + local.getPort() + "=>" + remote.getAddress().getHostAddress() + ":" + remote.getPort(); - } + @Override + public String toString() + { + InetSocketAddress local = channel.localAddress(); + InetSocketAddress remote = channel.remoteAddress(); + return local.getAddress().getHostAddress() + ":" + local.getPort() + "=>" + remote.getAddress().getHostAddress() + ":" + remote.getPort(); + } - /** - * 杩滅▼鍦板潃 - * - * @return - */ - public InetSocketAddress remoteAddress() - { - return channel.remoteAddress(); - } + /** + * 杩滅▼鍦板潃 + * + * @return + */ + public InetSocketAddress remoteAddress() + { + return channel.remoteAddress(); + } - /** - * 鏈湴鍦板潃 - * - * @return - */ - public InetSocketAddress localAddress() - { - return channel.localAddress(); - } + /** + * 鏈湴鍦板潃 + * + * @return + */ + public InetSocketAddress localAddress() + { + return channel.localAddress(); + } - public void setListener(SocketListener listener) - { - this.listener = listener; - } + public void setListener(SocketListener listener) + { + this.listener = listener; + } - public SocketListener getListener() - { - return listener; - } + public SocketListener getListener() + { + return listener; + } - /** - * 鑾峰彇channel - * - * @return - */ - public SocketChannel channel() - { - return channel; - } + /** + * 鑾峰彇channel + * + * @return + */ + public SocketChannel channel() + { + return channel; + } - /** - * 鏂紑鍘熷洜 - * - * @return - */ - public String getCloseReason() - { - return closeReasonString; - } + /** + * 鏂紑鍘熷洜 + * + * @return + */ + public String getCloseReason() + { + return closeReasonString; + } - /** - * 璁剧疆idle - * - * @param readerIdleTime - * @param writerIdleTime - * @param allIdleTime - * @param unit - */ - public void idle(long readerIdleTime, long writerIdleTime, long allIdleTime, TimeUnit unit) - { - ChannelHandler ch = channel.pipeline().first(); - if (ch instanceof IdleStateHandler) - { - channel.pipeline().removeFirst(); - } - channel.pipeline().addFirst(new IdleStateHandler(readerIdleTime, writerIdleTime, allIdleTime, unit)); - } + /** + * 璁剧疆idle + * + * @param readerIdleTime + * @param writerIdleTime + * @param allIdleTime + * @param unit + */ + public void idle(long readerIdleTime, long writerIdleTime, long allIdleTime, TimeUnit unit) + { + ChannelHandler ch = channel.pipeline().first(); + if (ch instanceof IdleStateHandler) + { + channel.pipeline().removeFirst(); + } + channel.pipeline().addFirst(new IdleStateHandler(readerIdleTime, writerIdleTime, allIdleTime, unit)); + } - /** - * 璁$畻璇籭dle - * - * @return - */ - public long readerIdle() - { - ChannelHandler ch = channel.pipeline().first(); - if (ch instanceof IdleStateHandler) - { - IdleStateHandler ish = (IdleStateHandler) ch; - return ish.getReaderIdleTimeInMillis(); - } - return 0; - } + /** + * 璁$畻璇籭dle + * + * @return + */ + public long readerIdle() + { + ChannelHandler ch = channel.pipeline().first(); + if (ch instanceof IdleStateHandler) + { + IdleStateHandler ish = (IdleStateHandler) ch; + return ish.getReaderIdleTimeInMillis(); + } + return 0; + } - /** - * 璁$畻鍐檌dle - * - * @return - */ - public long writerIdle() - { - ChannelHandler ch = channel.pipeline().first(); - if (ch instanceof IdleStateHandler) - { - IdleStateHandler ish = (IdleStateHandler) ch; - return ish.getWriterIdleTimeInMillis(); - } - return 0; - } + /** + * 璁$畻鍐檌dle + * + * @return + */ + public long writerIdle() + { + ChannelHandler ch = channel.pipeline().first(); + if (ch instanceof IdleStateHandler) + { + IdleStateHandler ish = (IdleStateHandler) ch; + return ish.getWriterIdleTimeInMillis(); + } + return 0; + } - /** - * 璁$畻all idle - * - * @return - */ - public long allIdle() - { - ChannelHandler ch = channel.pipeline().first(); - if (ch instanceof IdleStateHandler) - { - IdleStateHandler ish = (IdleStateHandler) ch; - return ish.getAllIdleTimeInMillis(); - } - return 0; - } + /** + * 璁$畻all idle + * + * @return + */ + public long allIdle() + { + ChannelHandler ch = channel.pipeline().first(); + if (ch instanceof IdleStateHandler) + { + IdleStateHandler ish = (IdleStateHandler) ch; + return ish.getAllIdleTimeInMillis(); + } + return 0; + } - /** - * 鏄惁涓篽ttp鍗忚 - * - * @param http - */ - public void setHttp(boolean http) - { - this.http = http; - } + /** + * 鏄惁涓篽ttp鍗忚 + * + * @param http + */ + public void setHttp(boolean http) + { + this.http = http; + } - /** - * 鏄惁涓篽ttp鍗忚 - * - * @return - */ - public boolean isHttp() - { - return http; - } + /** + * 鏄惁涓篽ttp鍗忚 + * + * @return + */ + public boolean isHttp() + { + return http; + } - /** - * 鏄惁涓篶lient绔 - * - * @param client - */ - public void setClient(boolean client) - { - this.client = client; - } + /** + * 鏄惁涓篶lient绔 + * + * @param client + */ + public void setClient(boolean client) + { + this.client = client; + } - /** - * 鏄惁涓哄鎴风 - * - * @return - */ - public boolean isClient() - { - return client; - } + /** + * 鏄惁涓哄鎴风 + * + * @return + */ + public boolean isClient() + { + return client; + } - /** - * uri - * - * @param uri - */ - public void setURI(String uri) - { - this.uri = uri; - } + /** + * uri + * + * @param uri + */ + public void setURI(String uri) + { + this.uri = uri; + } } diff --git a/cocosocket-server/src/org/ngame/socket/framing/Framedata.java b/cocosocket-server/src/org/ngame/socket/framing/Framedata.java index dd66c70..4e57149 100644 --- a/cocosocket-server/src/org/ngame/socket/framing/Framedata.java +++ b/cocosocket-server/src/org/ngame/socket/framing/Framedata.java @@ -132,9 +132,15 @@ public class Framedata { if (!end) { - byte[] b = s.getBytes(); - payload.writeShort(b.length); - payload.writeBytes(b); + try + { + byte[] b = s.getBytes("utf-8"); + payload.writeShort(b.length); + payload.writeBytes(b); + } catch (UnsupportedEncodingException ex) + { + ex.printStackTrace(); + } } return this; } @@ -150,10 +156,16 @@ public class Framedata { if (!end) { - byte[] b = s.getBytes(); - payload.writeShort(b.length); - xor(b, ks); - payload.writeBytes(b); + try + { + byte[] b = s.getBytes("utf-8"); + payload.writeShort(b.length); + xor(b, ks); + payload.writeBytes(b); + } catch (UnsupportedEncodingException ex) + { + ex.printStackTrace(); + } } return this; } diff --git a/cocosocket-server/src/org/ngame/socket/protocol/LVProtocol.java b/cocosocket-server/src/org/ngame/socket/protocol/LVProtocol.java index 3d5dab8..491aa49 100644 --- a/cocosocket-server/src/org/ngame/socket/protocol/LVProtocol.java +++ b/cocosocket-server/src/org/ngame/socket/protocol/LVProtocol.java @@ -3,12 +3,12 @@ package org.ngame.socket.protocol; import io.netty.buffer.ByteBuf; import io.netty.buffer.PooledByteBufAllocator; import io.netty.util.internal.PlatformDependent; -import java.nio.ByteOrder; -import java.util.logging.Level; -import java.util.logging.Logger; import org.ngame.socket.exeptions.InvalidDataException; import org.ngame.socket.exeptions.LimitExedeedException; +import java.nio.ByteOrder; +import java.util.logging.Logger; + /** * 瀛楄妭娴佸崗璁殑瀹炵幇 * @@ -17,80 +17,80 @@ import org.ngame.socket.exeptions.LimitExedeedException; public class LVProtocol extends Protocol { - private static final Logger LOG = Logger.getLogger(LVProtocol.class.getName()); - private ByteBuf incompleteframe;//灏氭湭瀹屾垚鐨勫抚 - private byte h, l;//楂樹綆瀛楄妭鐢ㄦ潵璁板綍闀垮害 - private byte status;//褰撳墠鐘舵 - private static final byte STATUS_H = 0; - private static final byte STATUS_L = 1; - private static final byte STATUS_C = 2; - private static int maxFrameSize = 2048;//鏈澶у抚闀垮害 + private static final Logger LOG = Logger.getLogger(LVProtocol.class.getName()); + private ByteBuf incompleteframe;//灏氭湭瀹屾垚鐨勫抚 + private byte h, l;//楂樹綆瀛楄妭鐢ㄦ潵璁板綍闀垮害 + private byte status;//褰撳墠鐘舵 + private static final byte STATUS_H = 0; + private static final byte STATUS_L = 1; + private static final byte STATUS_C = 2; + private int maxFrameSize = Integer.MAX_VALUE;//鏈澶у抚闀垮害 - static - { - try - { - maxFrameSize = Integer.parseInt(System.getProperty("game.socket.protocol.maxFrameSize")); - } catch (Exception e) - { - LOG.log(Level.WARNING, "socket甯ч暱搴﹁缃敊璇紝灏嗕娇鐢ㄩ粯璁ゅ"); - } - } - /** - * 鏋勯 - */ - public LVProtocol() - { - } + /** + * 鏋勯 + */ + public LVProtocol() + { + } - @Override - public ByteBuf translateFrame(ByteBuf readBuffer) throws LimitExedeedException, InvalidDataException - { - while (readBuffer.isReadable()) - { - switch (status) - { - case STATUS_H: - h = readBuffer.readByte(); - status = STATUS_L; - break; - case STATUS_L: - l = readBuffer.readByte(); - final int blen = Protocol.order == ByteOrder.BIG_ENDIAN ? (0x0000ff00 & (h << 8)) | (0x000000ff & l) : (0x0000ff00 & (l << 8)) | (0x000000ff & h); - if (context != null) - { - if (blen <= 0 || blen > maxFrameSize) - { - throw new LimitExedeedException("甯ч暱搴﹂潪娉:" + h + "/" + l + ":" + blen); - } - } - incompleteframe = PooledByteBufAllocator.DEFAULT.buffer(blen + 16 + 2); - incompleteframe.order(Protocol.order); - incompleteframe.writeShort(blen); - status = STATUS_C; - break; - case STATUS_C: - int len = incompleteframe.writableBytes() - 16; - len = len < readBuffer.readableBytes() ? len : readBuffer.readableBytes(); - //incompleteframe.writeBytes(readBuffer, len); - if (readBuffer.hasMemoryAddress()) - { - PlatformDependent.copyMemory(readBuffer.memoryAddress() + readBuffer.readerIndex(), incompleteframe.memoryAddress() + incompleteframe.writerIndex(), len); - } else if (readBuffer.hasArray()) - { - PlatformDependent.copyMemory(readBuffer.array(), readBuffer.arrayOffset() + readBuffer.readerIndex(), incompleteframe.memoryAddress() + incompleteframe.writerIndex(), len); - } - incompleteframe.writerIndex(incompleteframe.writerIndex() + len); - readBuffer.readerIndex(readBuffer.readerIndex() + len); - if ((incompleteframe.writableBytes() - 16) <= 0) - { - status = STATUS_H; - return incompleteframe; - } - break; - } - } - return null; - } + public void setMaxFrameSize(int maxFrameSize) + { + this.maxFrameSize = maxFrameSize; + } + + public int getMaxFrameSize() + { + return maxFrameSize; + } + + @Override + public ByteBuf translateFrame(ByteBuf readBuffer) throws LimitExedeedException, InvalidDataException + { + while (readBuffer.isReadable()) + { + switch (status) + { + case STATUS_H: + h = readBuffer.readByte(); + status = STATUS_L; + break; + case STATUS_L: + l = readBuffer.readByte(); + final int blen = Protocol.order == ByteOrder.BIG_ENDIAN ? (0x0000ff00 & (h << 8)) | (0x000000ff & l) : (0x0000ff00 & (l << 8)) | (0x000000ff & h); + if (context != null) + { + if (blen <= 0 || blen > maxFrameSize) + { + throw new LimitExedeedException("甯ч暱搴﹂潪娉:" + h + "/" + l + ":" + blen); + } + } + incompleteframe = PooledByteBufAllocator.DEFAULT.buffer(blen + 16 + 2); + incompleteframe.order(Protocol.order); + incompleteframe.writeShort(blen); + status = STATUS_C; + break; + case STATUS_C: + int len = incompleteframe.writableBytes() - 16; + len = len < readBuffer.readableBytes() ? len : readBuffer.readableBytes(); + //incompleteframe.writeBytes(readBuffer, len); + if (readBuffer.hasMemoryAddress()) + { + PlatformDependent.copyMemory(readBuffer.memoryAddress() + readBuffer.readerIndex(), incompleteframe.memoryAddress() + incompleteframe.writerIndex(), len); + } else if (readBuffer.hasArray()) + { + PlatformDependent.copyMemory(readBuffer.array(), readBuffer.arrayOffset() + readBuffer.readerIndex(), incompleteframe.memoryAddress() + incompleteframe.writerIndex(), len); + } + incompleteframe.writerIndex(incompleteframe.writerIndex() + len); + readBuffer.readerIndex(readBuffer.readerIndex() + len); + if ((incompleteframe.writableBytes() - 16) <= 0) + { + status = STATUS_H; + return incompleteframe; + } + break; + } + } + return null; + } } diff --git a/cocosocket-server/src/org/ngame/socket/test/TestClient.java b/cocosocket-server/src/org/ngame/socket/test/TestClient.java index 3a2d2b5..e8680cc 100644 --- a/cocosocket-server/src/org/ngame/socket/test/TestClient.java +++ b/cocosocket-server/src/org/ngame/socket/test/TestClient.java @@ -95,7 +95,7 @@ public class TestClient extends SocketClient */ public static void main(String... args) { - TestClient tc = new TestClient(new InetSocketAddress(3210), new LVProtocol()); + TestClient tc = new TestClient(new InetSocketAddress(80), new LVProtocol()); tc.connect(); } diff --git a/cocosocket-server/src/org/ngame/socket/test/TestServer.java b/cocosocket-server/src/org/ngame/socket/test/TestServer.java index 020b844..ec0099c 100644 --- a/cocosocket-server/src/org/ngame/socket/test/TestServer.java +++ b/cocosocket-server/src/org/ngame/socket/test/TestServer.java @@ -6,7 +6,6 @@ package org.ngame.socket.test; import io.netty.buffer.ByteBuf; import io.netty.handler.timeout.IdleStateEvent; import java.net.InetSocketAddress; -import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import org.ngame.socket.NSocket; @@ -24,7 +23,7 @@ public class TestServer extends SocketServer public TestServer(InetSocketAddress address) { - super(address,false); + super(address,true); } @Override diff --git a/cocosocket4unity/cocosocket4unity.sln b/cocosocket4unity/cocosocket4unity.sln new file mode 100644 index 0000000..90f9ef6 --- /dev/null +++ b/cocosocket4unity/cocosocket4unity.sln @@ -0,0 +1,20 @@ +锘 +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "cocosocket4unity", "cocosocket4unity\cocosocket4unity.csproj", "{E227176C-3062-40D0-AB28-74EC87FD818E}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x86 = Debug|x86 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {E227176C-3062-40D0-AB28-74EC87FD818E}.Debug|x86.ActiveCfg = Debug|x86 + {E227176C-3062-40D0-AB28-74EC87FD818E}.Debug|x86.Build.0 = Debug|x86 + {E227176C-3062-40D0-AB28-74EC87FD818E}.Release|x86.ActiveCfg = Release|x86 + {E227176C-3062-40D0-AB28-74EC87FD818E}.Release|x86.Build.0 = Release|x86 + EndGlobalSection + GlobalSection(MonoDevelopProperties) = preSolution + StartupItem = cocosocket4unity\cocosocket4unity.csproj + EndGlobalSection +EndGlobal diff --git a/cocosocket4unity/cocosocket4unity.userprefs b/cocosocket4unity/cocosocket4unity.userprefs new file mode 100644 index 0000000..7dee673 --- /dev/null +++ b/cocosocket4unity/cocosocket4unity.userprefs @@ -0,0 +1,18 @@ +锘 + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/cocosocket4unity/cocosocket4unity/AssemblyInfo.cs b/cocosocket4unity/cocosocket4unity/AssemblyInfo.cs new file mode 100644 index 0000000..49b6418 --- /dev/null +++ b/cocosocket4unity/cocosocket4unity/AssemblyInfo.cs @@ -0,0 +1,27 @@ +using System.Reflection; +using System.Runtime.CompilerServices; + +// Information about this assembly is defined by the following attributes. +// Change them to the values specific to your project. + +[assembly: AssemblyTitle("cocosocket4unity")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("")] +[assembly: AssemblyCopyright("Administrator")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". +// The form "{Major}.{Minor}.*" will automatically update the build and revision, +// and "{Major}.{Minor}.{Build}.*" will update just the revision. + +[assembly: AssemblyVersion("1.0.*")] + +// The following attributes are used to specify the signing key for the assembly, +// if desired. See the Mono documentation for more information about signing. + +//[assembly: AssemblyDelaySign(false)] +//[assembly: AssemblyKeyFile("")] + diff --git a/cocosocket4unity/cocosocket4unity/ByteBuf.cs b/cocosocket4unity/cocosocket4unity/ByteBuf.cs new file mode 100644 index 0000000..8308b99 --- /dev/null +++ b/cocosocket4unity/cocosocket4unity/ByteBuf.cs @@ -0,0 +1,433 @@ +/** + * 缂撳啿鍖 + **/ +using System; +using System.Text; + +namespace cocosocket4unity +{ + public class ByteBuf + { + private int len; + private byte[] data; + private int readerIndex; + private int writerIndex; + private int markReader; + private int markWriter; + + /** + * 鍒濆鍖 + **/ + public ByteBuf (int capacity) + { + this.len = capacity; + this.data = new byte[len]; + readerIndex = 0; + writerIndex = 0; + markReader = 0; + markWriter = 0; + } + + /** + * 瀹归噺 + **/ + public int Capacity () + { + return len; + } + + /** + * 鎵╁ + */ + public ByteBuf Capacity (int nc) + { + if (nc > len) { + byte[] old = data; + data = new byte[nc]; + Array.Copy (old, data, len); + len = nc; + } + return this; + } + + /** + * 娓呴櫎鎺夋墍鏈夋爣璁 + * @return + **/ + public ByteBuf Clear () + { + readerIndex = 0; + writerIndex = 0; + markReader = 0; + markWriter = 0; + return this; + } + /** + * 鎷疯礉 + **/ + public ByteBuf Copy() + { + ByteBuf item = new ByteBuf(len); + Array.Copy (this.data, item.data, len); + item.readerIndex = readerIndex; + item.writerIndex = writerIndex; + item.markReader = markReader; + item.markWriter = markWriter; + return item; + } + /** + * 鑾峰彇涓涓瓧鑺 + **/ + public byte GetByte(int index) + { + if (index < len) + { + return data[index]; + } + return (byte)0; + } + /** + * 璇诲彇鍥涘瓧鑺傛暣褰 + **/ + public int GetInt(int index) + { + if (index + 3 < len) + { + int ret = ((int) data[index]) << 24; + ret |= ((int) data[index + 1]) << 16; + ret |= ((int) data[index + 2]) << 8; + ret |= ((int) data[index + 3]); + return ret; + } + return 0; + } + /** + * 璇诲彇涓ゅ瓧鑺傛暣褰 + **/ + public short GetShort(int index) + { + if (index + 1 < len) + { + short r1 = (short)(data[index] << 8); + short r2 = (short)(data[index + 1]); + short ret = (short)(r1 | r2); + return ret; + } + return 0; + } + /** + * 鏍囪璇 + **/ + public ByteBuf MarkReaderIndex() + { + markReader = readerIndex; + return this; + } + /** + * 鏍囪鍐 + **/ + public ByteBuf MarkWriterIndex() + { + markWriter = writerIndex; + return this; + } + /** + * 鍙啓闀垮害 + **/ + public int MaxWritableBytes() + { + return len - writerIndex; + } + /** + * 璇诲彇涓涓瓧鑺 + **/ + public byte ReadByte() + { + if (readerIndex < writerIndex) + { + byte ret = data[readerIndex++]; + return ret; + } + return (byte)0; + } + /** + * 璇诲彇鍥涘瓧鑺傛暣褰 + **/ + public int ReadInt() + { + if (readerIndex + 3 < writerIndex) + { + unchecked + { + int ret = (int)(((data [readerIndex++]) << 24) & 0xff000000); + ret |= (((data [readerIndex++]) << 16) & 0x00ff0000); + ret |= (((data [readerIndex++]) << 8) & 0x0000ff00); + ret |= (((data [readerIndex++])) & 0x000000ff); + return ret; + } + } + return 0; + } + /** + * 璇诲彇涓や釜瀛楄妭鐨勬暣褰 + **/ + public short ReadShort() + { + if (readerIndex + 1 < writerIndex) + { + int h = data[readerIndex++]; + int l = data[readerIndex++]&0x000000ff; + int len = ((h << 8)&0x0000ff00) | (l); + return (short)len; + } + return 0; + } + /** + * 鍙瀛楄妭鏁 + **/ + public int ReadableBytes() + { + return writerIndex - readerIndex; + } + /** + * 璇绘寚閽 + **/ + public int ReaderIndex() + { + return readerIndex; + } + /** + * 绉诲姩璇绘寚閽 + **/ + public ByteBuf ReaderIndex(int readerIndex) + { + if (readerIndex <= writerIndex) + { + this.readerIndex = readerIndex; + } + return this; + } + /** + * 閲嶇疆璇绘寚閽 + **/ + public ByteBuf ResetReaderIndex() + { + if (markReader <= writerIndex) + { + this.readerIndex = markReader; + } + return this; + } + /** + * 閲嶇疆鍐欐寚閽 + **/ + public ByteBuf ResetWriterIndex() + { + if (markWriter >= readerIndex) + { + writerIndex = markWriter; + } + return this; + } + /** + * 璁剧疆瀛楄妭 + **/ + public ByteBuf SetByte(int index, byte value) + { + if (index < len) + { + data[index] = value; + } + return this; + } + + + /** + * 璁剧疆瀛楄妭 + **/ + public ByteBuf SetBytes(int index, byte[] src, int from, int len) + { + if (index + len <= len) + { + Array.Copy (src, from, data, index, len); + } + return this; + } + /** + * 璁剧疆璇诲啓鎸囬拡 + **/ + public ByteBuf SetIndex(int readerIndex, int writerIndex) + { + if (readerIndex >= 0 && readerIndex <= writerIndex && writerIndex <= len) + { + this.readerIndex = readerIndex; + this.writerIndex = writerIndex; + } + return this; + } + /** + * 璁剧疆鍥涘瓧鑺傛暣褰 + **/ + public ByteBuf SetInt(int index, int value) + { + if (index + 4 <= len) + { + data[index++] = (byte)((value >> 24) & 0xff); + data[index++] = (byte)((value >> 16) & 0xff); + data[index++] = (byte)((value >> 8) & 0xff); + data[index++] = (byte)(value & 0xff); + } + return this; + } + /** + * 璁剧疆涓ゅ瓧鑺傛暣褰 + **/ + public ByteBuf SetShort(int index, short value) + { + if (index + 2 <= len) + { + data[index++] = (byte)((value >> 8) & 0xff); + data[index++] = (byte)(value & 0xff); + } + return this; + } + /** + * 鐣ヨ繃涓浜涘瓧鑺 + **/ + public ByteBuf SkipBytes(int length) + { + if (readerIndex + length <= writerIndex) + { + readerIndex += length; + } + return this; + } + /** + * 鍓╀綑鐨勫彲鍐欏瓧鑺傛暟 + **/ + public int WritableBytes() + { + return len - writerIndex; + } + /** + * 鍐欏叆涓涓瓧鑺 + * + **/ + public ByteBuf WriteByte(byte value) + { + this.Capacity(writerIndex + 1); + this.data[writerIndex++] = value; + return this; + } + /** + * 鍐欏叆鍥涘瓧鑺傛暣褰 + **/ + public ByteBuf WriteInt(int value) + { + Capacity(writerIndex + 4); + data[writerIndex++] = (byte)((value >> 24) & 0xff); + data[writerIndex++] = (byte)((value >> 16) & 0xff); + data[writerIndex++] = (byte)((value >> 8) & 0xff); + data[writerIndex++] = (byte)(value & 0xff); + return this; + } + /** + * 鍐欏叆涓ゅ瓧鑺傛暣褰 + **/ + public ByteBuf WriteShort(short value) + { + Capacity(writerIndex + 2); + data[writerIndex++] = (byte)((value >> 8) & 0xff); + data[writerIndex++] = (byte)(value & 0xff); + return this; + } + /** + * 鍐欏叆涓閮ㄥ垎瀛楄妭 + **/ + public ByteBuf WriteBytes(ByteBuf src) + { + int sum = src.writerIndex - src.readerIndex; + Capacity(writerIndex + sum); + if (sum > 0) + { + Array.Copy (src.data, src.readerIndex, data, writerIndex, sum); + writerIndex += sum; + src.readerIndex += sum; + } + return this; + } + /** + * 鍐欏叆涓閮ㄥ垎瀛楄妭 + **/ + public ByteBuf WriteBytes(byte[] src) + { + int sum = src.Length; + Capacity(writerIndex + sum); + if (sum > 0) + { + Array.Copy (src, 0, data, writerIndex, sum); + writerIndex += sum; + } + return this; + } + /** + * 璇诲彇utf瀛楃涓 + **/ + public string ReadUTF8() + { + short len = ReadShort(); // 瀛楄妭鏁 + byte[] charBuff = new byte[len]; // + Array.Copy (data, readerIndex, charBuff, 0, len); + readerIndex += len; + return Encoding.UTF8.GetString (charBuff); + } + + /** + * 鍐欏叆utf瀛楃涓 + * + **/ + public ByteBuf WriteUTF8(string value) + { + byte[] content = Encoding.UTF8.GetBytes (value.ToCharArray()); + int len = content.Length; + Capacity(writerIndex + len + 2); + WriteShort((short) len); + Array.Copy (content, 0, data, writerIndex, len); + writerIndex += len; + return this; + } + /** + * 鍐欐寚閽 + **/ + public int WriterIndex() + { + return writerIndex; + } + /** + * 绉诲姩鍐欐寚閽 + **/ + public ByteBuf WriterIndex(int writerIndex) + { + if (writerIndex >= readerIndex && writerIndex <= len) + { + this.writerIndex = writerIndex; + } + return this; + } + /** + * 鍘熷瀛楄妭鏁扮粍 + **/ + public byte[] GetRaw() + { + return data; + } + + + + + + + + } +} + diff --git a/cocosocket4unity/cocosocket4unity/Frame.cs b/cocosocket4unity/cocosocket4unity/Frame.cs new file mode 100644 index 0000000..2fbc4d0 --- /dev/null +++ b/cocosocket4unity/cocosocket4unity/Frame.cs @@ -0,0 +1,149 @@ +锘縰sing System; +using System.Text; + +namespace cocosocket4unity +{ + public class Frame + { + private ByteBuf payload; + private bool end; + public Frame (int len) + { + this.payload = new ByteBuf (len); + payload.WriteShort(0); + } + /** + * 鑾峰彇缂撳啿鍖 + **/ + public ByteBuf GetData() + { + return payload; + } + /** + * 鍐欏叆涓涓瓧鑺 + **/ + public Frame PutByte(byte c) + { + if (!end) + payload.WriteByte(c); + return this; + } + /** + * 鍐欏叆涓浜涘瓧鑺 + **/ + public Frame PutBytes(ByteBuf src) + { + if (!end) + payload.WriteBytes(src); + return this; + } + + /** + * 鍐欏叆鏁村舰 + **/ + public Frame PutInt(int s) + { + if (!end) + payload.WriteInt(s); + return this; + } + /** + * 鍐欏叆鐭暣鍨 + **/ + public Frame PutShort(short s) + { + if (!end) + payload.WriteShort(s); + return this; + } + /** + * 鍐欏叆涓涓瓧绗︿覆 + **/ + public Frame PutString(string s) + { + if (!end) + payload.WriteUTF8(s); + return this; + } + /** + * 鍐欏叆涓涓瓧绗︿覆 + **/ + public Frame PutString(string s,byte[] ks) + { + if (!end) + { + byte[] content = Encoding.UTF8.GetBytes (s.ToCharArray ()); + this.payload.WriteShort ((short)content.Length); + xor (content, ks); + this.payload.WriteBytes (content); + } + return this; + } + /** + * 娴呮嫹璐 + **/ + public Frame Duplicate() + { + Frame f = new Frame(payload.Capacity()); + payload.MarkReaderIndex(); + f.PutBytes(payload); + payload.ResetReaderIndex(); + if (end) + { + f.End(); + } + return f; + } + /** + * 灏佸寘 + **/ + public void End() + { + ByteBuf bb = payload; + int reader = bb.ReaderIndex(); + int writer = bb.WriterIndex(); + int l = writer - reader - 2; //鏁版嵁闀垮害 + bb.WriterIndex(reader); + bb.WriteShort((short)l); + bb.WriterIndex(writer); + end = true; + } + /** + * 鏄惁宸茬粡灏佸寘 + **/ + public bool IsEnd() + { + return end; + } + /** + * 璁剧疆end鏍囩ず + **/ + public void SetEnd(bool e) + { + if (e) + { + End(); + } else + { + end = e; + } + } + /** + * 鍙栧紓鎴 + * + * @param bs + * @param ks + */ + public static void xor(byte[] bs, byte[] ks) + { + if (ks != null && ks.Length > 0) + { + for (int i = 0; i < bs.Length; i++) + { + bs[i] = (byte) (bs[i] ^ ks[i % ks.Length]); + } + } + } + } +} + diff --git a/cocosocket4unity/cocosocket4unity/IJsonWrapper.cs b/cocosocket4unity/cocosocket4unity/IJsonWrapper.cs new file mode 100644 index 0000000..9b7e2d1 --- /dev/null +++ b/cocosocket4unity/cocosocket4unity/IJsonWrapper.cs @@ -0,0 +1,60 @@ +#region Header +/** + * IJsonWrapper.cs + * Interface that represents a type capable of handling all kinds of JSON + * data. This is mainly used when mapping objects through JsonMapper, and + * it's implemented by JsonData. + * + * The authors disclaim copyright to this source code. For more details, see + * the COPYING file included with this distribution. + **/ +#endregion + + +using System.Collections; +using System.Collections.Specialized; + + +namespace LitJson +{ + public enum JsonType + { + None, + + Object, + Array, + String, + Int, + Long, + Double, + Boolean + } + + public interface IJsonWrapper : IList, IOrderedDictionary + { + bool IsArray { get; } + bool IsBoolean { get; } + bool IsDouble { get; } + bool IsInt { get; } + bool IsLong { get; } + bool IsObject { get; } + bool IsString { get; } + + bool GetBoolean (); + double GetDouble (); + int GetInt (); + JsonType GetJsonType (); + long GetLong (); + string GetString (); + + void SetBoolean (bool val); + void SetDouble (double val); + void SetInt (int val); + void SetJsonType (JsonType type); + void SetLong (long val); + void SetString (string val); + + string ToJson (); + void ToJson (JsonWriter writer); + } +} diff --git a/cocosocket4unity/cocosocket4unity/JsonData.cs b/cocosocket4unity/cocosocket4unity/JsonData.cs new file mode 100644 index 0000000..ccc5687 --- /dev/null +++ b/cocosocket4unity/cocosocket4unity/JsonData.cs @@ -0,0 +1,993 @@ +#region Header +/** + * JsonData.cs + * Generic type to hold JSON data (objects, arrays, and so on). This is + * the default type returned by JsonMapper.ToObject(). + * + * The authors disclaim copyright to this source code. For more details, see + * the COPYING file included with this distribution. + **/ +#endregion + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.IO; + + +namespace LitJson +{ + public class JsonData : IJsonWrapper, IEquatable + { + #region Fields + private IList inst_array; + private bool inst_boolean; + private double inst_double; + private int inst_int; + private long inst_long; + private IDictionary inst_object; + private string inst_string; + private string json; + private JsonType type; + + // Used to implement the IOrderedDictionary interface + private IList> object_list; + #endregion + + + #region Properties + public int Count { + get { return EnsureCollection ().Count; } + } + + public bool IsArray { + get { return type == JsonType.Array; } + } + + public bool IsBoolean { + get { return type == JsonType.Boolean; } + } + + public bool IsDouble { + get { return type == JsonType.Double; } + } + + public bool IsInt { + get { return type == JsonType.Int; } + } + + public bool IsLong { + get { return type == JsonType.Long; } + } + + public bool IsObject { + get { return type == JsonType.Object; } + } + + public bool IsString { + get { return type == JsonType.String; } + } + #endregion + + + #region ICollection Properties + int ICollection.Count { + get { + return Count; + } + } + + bool ICollection.IsSynchronized { + get { + return EnsureCollection ().IsSynchronized; + } + } + + object ICollection.SyncRoot { + get { + return EnsureCollection ().SyncRoot; + } + } + #endregion + + + #region IDictionary Properties + bool IDictionary.IsFixedSize { + get { + return EnsureDictionary ().IsFixedSize; + } + } + + bool IDictionary.IsReadOnly { + get { + return EnsureDictionary ().IsReadOnly; + } + } + + ICollection IDictionary.Keys { + get { + EnsureDictionary (); + IList keys = new List (); + + foreach (KeyValuePair entry in + object_list) { + keys.Add (entry.Key); + } + + return (ICollection) keys; + } + } + + ICollection IDictionary.Values { + get { + EnsureDictionary (); + IList values = new List (); + + foreach (KeyValuePair entry in + object_list) { + values.Add (entry.Value); + } + + return (ICollection) values; + } + } + #endregion + + + + #region IJsonWrapper Properties + bool IJsonWrapper.IsArray { + get { return IsArray; } + } + + bool IJsonWrapper.IsBoolean { + get { return IsBoolean; } + } + + bool IJsonWrapper.IsDouble { + get { return IsDouble; } + } + + bool IJsonWrapper.IsInt { + get { return IsInt; } + } + + bool IJsonWrapper.IsLong { + get { return IsLong; } + } + + bool IJsonWrapper.IsObject { + get { return IsObject; } + } + + bool IJsonWrapper.IsString { + get { return IsString; } + } + #endregion + + + #region IList Properties + bool IList.IsFixedSize { + get { + return EnsureList ().IsFixedSize; + } + } + + bool IList.IsReadOnly { + get { + return EnsureList ().IsReadOnly; + } + } + #endregion + + + #region IDictionary Indexer + object IDictionary.this[object key] { + get { + return EnsureDictionary ()[key]; + } + + set { + if (! (key is String)) + throw new ArgumentException ( + "The key has to be a string"); + + JsonData data = ToJsonData (value); + + this[(string) key] = data; + } + } + #endregion + + + #region IOrderedDictionary Indexer + object IOrderedDictionary.this[int idx] { + get { + EnsureDictionary (); + return object_list[idx].Value; + } + + set { + EnsureDictionary (); + JsonData data = ToJsonData (value); + + KeyValuePair old_entry = object_list[idx]; + + inst_object[old_entry.Key] = data; + + KeyValuePair entry = + new KeyValuePair (old_entry.Key, data); + + object_list[idx] = entry; + } + } + #endregion + + + #region IList Indexer + object IList.this[int index] { + get { + return EnsureList ()[index]; + } + + set { + EnsureList (); + JsonData data = ToJsonData (value); + + this[index] = data; + } + } + #endregion + + + #region Public Indexers + public JsonData this[string prop_name] { + get { + EnsureDictionary (); + return inst_object[prop_name]; + } + + set { + EnsureDictionary (); + + KeyValuePair entry = + new KeyValuePair (prop_name, value); + + if (inst_object.ContainsKey (prop_name)) { + for (int i = 0; i < object_list.Count; i++) { + if (object_list[i].Key == prop_name) { + object_list[i] = entry; + break; + } + } + } else + object_list.Add (entry); + + inst_object[prop_name] = value; + + json = null; + } + } + + public JsonData this[int index] { + get { + EnsureCollection (); + + if (type == JsonType.Array) + return inst_array[index]; + + return object_list[index].Value; + } + + set { + EnsureCollection (); + + if (type == JsonType.Array) + inst_array[index] = value; + else { + KeyValuePair entry = object_list[index]; + KeyValuePair new_entry = + new KeyValuePair (entry.Key, value); + + object_list[index] = new_entry; + inst_object[entry.Key] = value; + } + + json = null; + } + } + #endregion + + + #region Constructors + public JsonData () + { + } + + public JsonData (bool boolean) + { + type = JsonType.Boolean; + inst_boolean = boolean; + } + + public JsonData (double number) + { + type = JsonType.Double; + inst_double = number; + } + + public JsonData (int number) + { + type = JsonType.Int; + inst_int = number; + } + + public JsonData (long number) + { + type = JsonType.Long; + inst_long = number; + } + + public JsonData (object obj) + { + if (obj is Boolean) { + type = JsonType.Boolean; + inst_boolean = (bool) obj; + return; + } + + if (obj is Double) { + type = JsonType.Double; + inst_double = (double) obj; + return; + } + + if (obj is Int32) { + type = JsonType.Int; + inst_int = (int) obj; + return; + } + + if (obj is Int64) { + type = JsonType.Long; + inst_long = (long) obj; + return; + } + + if (obj is String) { + type = JsonType.String; + inst_string = (string) obj; + return; + } + + throw new ArgumentException ( + "Unable to wrap the given object with JsonData"); + } + + public JsonData (string str) + { + type = JsonType.String; + inst_string = str; + } + #endregion + + + #region Implicit Conversions + public static implicit operator JsonData (Boolean data) + { + return new JsonData (data); + } + + public static implicit operator JsonData (Double data) + { + return new JsonData (data); + } + + public static implicit operator JsonData (Int32 data) + { + return new JsonData (data); + } + + public static implicit operator JsonData (Int64 data) + { + return new JsonData (data); + } + + public static implicit operator JsonData (String data) + { + return new JsonData (data); + } + #endregion + + + #region Explicit Conversions + public static explicit operator Boolean (JsonData data) + { + if (data.type != JsonType.Boolean) + throw new InvalidCastException ( + "Instance of JsonData doesn't hold a double"); + + return data.inst_boolean; + } + + public static explicit operator Double (JsonData data) + { + if (data.type != JsonType.Double) + throw new InvalidCastException ( + "Instance of JsonData doesn't hold a double"); + + return data.inst_double; + } + + public static explicit operator Int32 (JsonData data) + { + if (data.type != JsonType.Int) + throw new InvalidCastException ( + "Instance of JsonData doesn't hold an int"); + + return data.inst_int; + } + + public static explicit operator Int64 (JsonData data) + { + if (data.type != JsonType.Long) + throw new InvalidCastException ( + "Instance of JsonData doesn't hold an int"); + + return data.inst_long; + } + + public static explicit operator String (JsonData data) + { + if (data.type != JsonType.String) + throw new InvalidCastException ( + "Instance of JsonData doesn't hold a string"); + + return data.inst_string; + } + #endregion + + + #region ICollection Methods + void ICollection.CopyTo (Array array, int index) + { + EnsureCollection ().CopyTo (array, index); + } + #endregion + + + #region IDictionary Methods + void IDictionary.Add (object key, object value) + { + JsonData data = ToJsonData (value); + + EnsureDictionary ().Add (key, data); + + KeyValuePair entry = + new KeyValuePair ((string) key, data); + object_list.Add (entry); + + json = null; + } + + void IDictionary.Clear () + { + EnsureDictionary ().Clear (); + object_list.Clear (); + json = null; + } + + bool IDictionary.Contains (object key) + { + return EnsureDictionary ().Contains (key); + } + + IDictionaryEnumerator IDictionary.GetEnumerator () + { + return ((IOrderedDictionary) this).GetEnumerator (); + } + + void IDictionary.Remove (object key) + { + EnsureDictionary ().Remove (key); + + for (int i = 0; i < object_list.Count; i++) { + if (object_list[i].Key == (string) key) { + object_list.RemoveAt (i); + break; + } + } + + json = null; + } + #endregion + + + #region IEnumerable Methods + IEnumerator IEnumerable.GetEnumerator () + { + return EnsureCollection ().GetEnumerator (); + } + #endregion + + + #region IJsonWrapper Methods + bool IJsonWrapper.GetBoolean () + { + if (type != JsonType.Boolean) + throw new InvalidOperationException ( + "JsonData instance doesn't hold a boolean"); + + return inst_boolean; + } + + double IJsonWrapper.GetDouble () + { + if (type != JsonType.Double) + throw new InvalidOperationException ( + "JsonData instance doesn't hold a double"); + + return inst_double; + } + + int IJsonWrapper.GetInt () + { + if (type != JsonType.Int) + throw new InvalidOperationException ( + "JsonData instance doesn't hold an int"); + + return inst_int; + } + + long IJsonWrapper.GetLong () + { + if (type != JsonType.Long) + throw new InvalidOperationException ( + "JsonData instance doesn't hold a long"); + + return inst_long; + } + + string IJsonWrapper.GetString () + { + if (type != JsonType.String) + throw new InvalidOperationException ( + "JsonData instance doesn't hold a string"); + + return inst_string; + } + + void IJsonWrapper.SetBoolean (bool val) + { + type = JsonType.Boolean; + inst_boolean = val; + json = null; + } + + void IJsonWrapper.SetDouble (double val) + { + type = JsonType.Double; + inst_double = val; + json = null; + } + + void IJsonWrapper.SetInt (int val) + { + type = JsonType.Int; + inst_int = val; + json = null; + } + + void IJsonWrapper.SetLong (long val) + { + type = JsonType.Long; + inst_long = val; + json = null; + } + + void IJsonWrapper.SetString (string val) + { + type = JsonType.String; + inst_string = val; + json = null; + } + + string IJsonWrapper.ToJson () + { + return ToJson (); + } + + void IJsonWrapper.ToJson (JsonWriter writer) + { + ToJson (writer); + } + #endregion + + + #region IList Methods + int IList.Add (object value) + { + return Add (value); + } + + void IList.Clear () + { + EnsureList ().Clear (); + json = null; + } + + bool IList.Contains (object value) + { + return EnsureList ().Contains (value); + } + + int IList.IndexOf (object value) + { + return EnsureList ().IndexOf (value); + } + + void IList.Insert (int index, object value) + { + EnsureList ().Insert (index, value); + json = null; + } + + void IList.Remove (object value) + { + EnsureList ().Remove (value); + json = null; + } + + void IList.RemoveAt (int index) + { + EnsureList ().RemoveAt (index); + json = null; + } + #endregion + + + #region IOrderedDictionary Methods + IDictionaryEnumerator IOrderedDictionary.GetEnumerator () + { + EnsureDictionary (); + + return new OrderedDictionaryEnumerator ( + object_list.GetEnumerator ()); + } + + void IOrderedDictionary.Insert (int idx, object key, object value) + { + string property = (string) key; + JsonData data = ToJsonData (value); + + this[property] = data; + + KeyValuePair entry = + new KeyValuePair (property, data); + + object_list.Insert (idx, entry); + } + + void IOrderedDictionary.RemoveAt (int idx) + { + EnsureDictionary (); + + inst_object.Remove (object_list[idx].Key); + object_list.RemoveAt (idx); + } + #endregion + + + #region Private Methods + private ICollection EnsureCollection () + { + if (type == JsonType.Array) + return (ICollection) inst_array; + + if (type == JsonType.Object) + return (ICollection) inst_object; + + throw new InvalidOperationException ( + "The JsonData instance has to be initialized first"); + } + + private IDictionary EnsureDictionary () + { + if (type == JsonType.Object) + return (IDictionary) inst_object; + + if (type != JsonType.None) + throw new InvalidOperationException ( + "Instance of JsonData is not a dictionary"); + + type = JsonType.Object; + inst_object = new Dictionary (); + object_list = new List> (); + + return (IDictionary) inst_object; + } + + private IList EnsureList () + { + if (type == JsonType.Array) + return (IList) inst_array; + + if (type != JsonType.None) + throw new InvalidOperationException ( + "Instance of JsonData is not a list"); + + type = JsonType.Array; + inst_array = new List (); + + return (IList) inst_array; + } + + private JsonData ToJsonData (object obj) + { + if (obj == null) + return null; + + if (obj is JsonData) + return (JsonData) obj; + + return new JsonData (obj); + } + + private static void WriteJson (IJsonWrapper obj, JsonWriter writer) + { + if (obj.IsString) { + writer.Write (obj.GetString ()); + return; + } + + if (obj.IsBoolean) { + writer.Write (obj.GetBoolean ()); + return; + } + + if (obj.IsDouble) { + writer.Write (obj.GetDouble ()); + return; + } + + if (obj.IsInt) { + writer.Write (obj.GetInt ()); + return; + } + + if (obj.IsLong) { + writer.Write (obj.GetLong ()); + return; + } + + if (obj.IsArray) { + writer.WriteArrayStart (); + foreach (object elem in (IList) obj) + WriteJson ((JsonData) elem, writer); + writer.WriteArrayEnd (); + + return; + } + + if (obj.IsObject) { + writer.WriteObjectStart (); + + foreach (DictionaryEntry entry in ((IDictionary) obj)) { + writer.WritePropertyName ((string) entry.Key); + WriteJson ((JsonData) entry.Value, writer); + } + writer.WriteObjectEnd (); + + return; + } + } + #endregion + + + public int Add (object value) + { + JsonData data = ToJsonData (value); + + json = null; + + return EnsureList ().Add (data); + } + + public void Clear () + { + if (IsObject) { + ((IDictionary) this).Clear (); + return; + } + + if (IsArray) { + ((IList) this).Clear (); + return; + } + } + + public bool Equals (JsonData x) + { + if (x == null) + return false; + + if (x.type != this.type) + return false; + + switch (this.type) { + case JsonType.None: + return true; + + case JsonType.Object: + return this.inst_object.Equals (x.inst_object); + + case JsonType.Array: + return this.inst_array.Equals (x.inst_array); + + case JsonType.String: + return this.inst_string.Equals (x.inst_string); + + case JsonType.Int: + return this.inst_int.Equals (x.inst_int); + + case JsonType.Long: + return this.inst_long.Equals (x.inst_long); + + case JsonType.Double: + return this.inst_double.Equals (x.inst_double); + + case JsonType.Boolean: + return this.inst_boolean.Equals (x.inst_boolean); + } + + return false; + } + + public JsonType GetJsonType () + { + return type; + } + + public void SetJsonType (JsonType type) + { + if (this.type == type) + return; + + switch (type) { + case JsonType.None: + break; + + case JsonType.Object: + inst_object = new Dictionary (); + object_list = new List> (); + break; + + case JsonType.Array: + inst_array = new List (); + break; + + case JsonType.String: + inst_string = default (String); + break; + + case JsonType.Int: + inst_int = default (Int32); + break; + + case JsonType.Long: + inst_long = default (Int64); + break; + + case JsonType.Double: + inst_double = default (Double); + break; + + case JsonType.Boolean: + inst_boolean = default (Boolean); + break; + } + + this.type = type; + } + + public string ToJson () + { + if (json != null) + return json; + + StringWriter sw = new StringWriter (); + JsonWriter writer = new JsonWriter (sw); + writer.Validate = false; + + WriteJson (this, writer); + json = sw.ToString (); + + return json; + } + + public void ToJson (JsonWriter writer) + { + bool old_validate = writer.Validate; + + writer.Validate = false; + + WriteJson (this, writer); + + writer.Validate = old_validate; + } + + public override string ToString () + { + switch (type) { + case JsonType.Array: + return "JsonData array"; + + case JsonType.Boolean: + return inst_boolean.ToString (); + + case JsonType.Double: + return inst_double.ToString (); + + case JsonType.Int: + return inst_int.ToString (); + + case JsonType.Long: + return inst_long.ToString (); + + case JsonType.Object: + return "JsonData object"; + + case JsonType.String: + return inst_string; + } + + return "Uninitialized JsonData"; + } + } + + + internal class OrderedDictionaryEnumerator : IDictionaryEnumerator + { + IEnumerator> list_enumerator; + + + public object Current { + get { return Entry; } + } + + public DictionaryEntry Entry { + get { + KeyValuePair curr = list_enumerator.Current; + return new DictionaryEntry (curr.Key, curr.Value); + } + } + + public object Key { + get { return list_enumerator.Current.Key; } + } + + public object Value { + get { return list_enumerator.Current.Value; } + } + + + public OrderedDictionaryEnumerator ( + IEnumerator> enumerator) + { + list_enumerator = enumerator; + } + + + public bool MoveNext () + { + return list_enumerator.MoveNext (); + } + + public void Reset () + { + list_enumerator.Reset (); + } + } +} diff --git a/cocosocket4unity/cocosocket4unity/JsonException.cs b/cocosocket4unity/cocosocket4unity/JsonException.cs new file mode 100644 index 0000000..8ad6f0a --- /dev/null +++ b/cocosocket4unity/cocosocket4unity/JsonException.cs @@ -0,0 +1,60 @@ +#region Header +/** + * JsonException.cs + * Base class throwed by LitJSON when a parsing error occurs. + * + * The authors disclaim copyright to this source code. For more details, see + * the COPYING file included with this distribution. + **/ +#endregion + + +using System; + + +namespace LitJson +{ + public class JsonException : ApplicationException + { + public JsonException () : base () + { + } + + internal JsonException (ParserToken token) : + base (String.Format ( + "Invalid token '{0}' in input string", token)) + { + } + + internal JsonException (ParserToken token, + Exception inner_exception) : + base (String.Format ( + "Invalid token '{0}' in input string", token), + inner_exception) + { + } + + internal JsonException (int c) : + base (String.Format ( + "Invalid character '{0}' in input string", (char) c)) + { + } + + internal JsonException (int c, Exception inner_exception) : + base (String.Format ( + "Invalid character '{0}' in input string", (char) c), + inner_exception) + { + } + + + public JsonException (string message) : base (message) + { + } + + public JsonException (string message, Exception inner_exception) : + base (message, inner_exception) + { + } + } +} diff --git a/cocosocket4unity/cocosocket4unity/JsonMapper.cs b/cocosocket4unity/cocosocket4unity/JsonMapper.cs new file mode 100644 index 0000000..5a6939b --- /dev/null +++ b/cocosocket4unity/cocosocket4unity/JsonMapper.cs @@ -0,0 +1,924 @@ +#region Header +/** + * JsonMapper.cs + * JSON to .Net object and object to JSON conversions. + * + * The authors disclaim copyright to this source code. For more details, see + * the COPYING file included with this distribution. + **/ +#endregion + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Reflection; + + +namespace LitJson +{ + internal struct PropertyMetadata + { + public MemberInfo Info; + public bool IsField; + public Type Type; + } + + + internal struct ArrayMetadata + { + private Type element_type; + private bool is_array; + private bool is_list; + + + public Type ElementType { + get { + if (element_type == null) + return typeof (JsonData); + + return element_type; + } + + set { element_type = value; } + } + + public bool IsArray { + get { return is_array; } + set { is_array = value; } + } + + public bool IsList { + get { return is_list; } + set { is_list = value; } + } + } + + + internal struct ObjectMetadata + { + private Type element_type; + private bool is_dictionary; + + private IDictionary properties; + + + public Type ElementType { + get { + if (element_type == null) + return typeof (JsonData); + + return element_type; + } + + set { element_type = value; } + } + + public bool IsDictionary { + get { return is_dictionary; } + set { is_dictionary = value; } + } + + public IDictionary Properties { + get { return properties; } + set { properties = value; } + } + } + + + internal delegate void ExporterFunc (object obj, JsonWriter writer); + public delegate void ExporterFunc (T obj, JsonWriter writer); + + internal delegate object ImporterFunc (object input); + public delegate TValue ImporterFunc (TJson input); + + public delegate IJsonWrapper WrapperFactory (); + + + public class JsonMapper + { + #region Fields + private static int max_nesting_depth; + + private static IFormatProvider datetime_format; + + private static IDictionary base_exporters_table; + private static IDictionary custom_exporters_table; + + private static IDictionary> base_importers_table; + private static IDictionary> custom_importers_table; + + private static IDictionary array_metadata; + private static readonly object array_metadata_lock = new Object (); + + private static IDictionary> conv_ops; + private static readonly object conv_ops_lock = new Object (); + + private static IDictionary object_metadata; + private static readonly object object_metadata_lock = new Object (); + + private static IDictionary> type_properties; + private static readonly object type_properties_lock = new Object (); + + private static JsonWriter static_writer; + private static readonly object static_writer_lock = new Object (); + #endregion + + + #region Constructors + static JsonMapper () + { + max_nesting_depth = 100; + + array_metadata = new Dictionary (); + conv_ops = new Dictionary> (); + object_metadata = new Dictionary (); + type_properties = new Dictionary> (); + + static_writer = new JsonWriter (); + + datetime_format = DateTimeFormatInfo.InvariantInfo; + + base_exporters_table = new Dictionary (); + custom_exporters_table = new Dictionary (); + + base_importers_table = new Dictionary> (); + custom_importers_table = new Dictionary> (); + + RegisterBaseExporters (); + RegisterBaseImporters (); + } + #endregion + + + #region Private Methods + private static void AddArrayMetadata (Type type) + { + if (array_metadata.ContainsKey (type)) + return; + + ArrayMetadata data = new ArrayMetadata (); + + data.IsArray = type.IsArray; + + if (type.GetInterface ("System.Collections.IList") != null) + data.IsList = true; + + foreach (PropertyInfo p_info in type.GetProperties ()) { + if (p_info.Name != "Item") + continue; + + ParameterInfo[] parameters = p_info.GetIndexParameters (); + + if (parameters.Length != 1) + continue; + + if (parameters[0].ParameterType == typeof (int)) + data.ElementType = p_info.PropertyType; + } + + lock (array_metadata_lock) { + try { + array_metadata.Add (type, data); + } catch (ArgumentException) { + return; + } + } + } + + private static void AddObjectMetadata (Type type) + { + if (object_metadata.ContainsKey (type)) + return; + + ObjectMetadata data = new ObjectMetadata (); + + if (type.GetInterface ("System.Collections.IDictionary") != null) + data.IsDictionary = true; + + data.Properties = new Dictionary (); + + foreach (PropertyInfo p_info in type.GetProperties ()) { + if (p_info.Name == "Item") { + ParameterInfo[] parameters = p_info.GetIndexParameters (); + + if (parameters.Length != 1) + continue; + + if (parameters[0].ParameterType == typeof (string)) + data.ElementType = p_info.PropertyType; + + continue; + } + + PropertyMetadata p_data = new PropertyMetadata (); + p_data.Info = p_info; + p_data.Type = p_info.PropertyType; + + data.Properties.Add (p_info.Name, p_data); + } + + foreach (FieldInfo f_info in type.GetFields ()) { + PropertyMetadata p_data = new PropertyMetadata (); + p_data.Info = f_info; + p_data.IsField = true; + p_data.Type = f_info.FieldType; + + data.Properties.Add (f_info.Name, p_data); + } + + lock (object_metadata_lock) { + try { + object_metadata.Add (type, data); + } catch (ArgumentException) { + return; + } + } + } + + private static void AddTypeProperties (Type type) + { + if (type_properties.ContainsKey (type)) + return; + + IList props = new List (); + + foreach (PropertyInfo p_info in type.GetProperties ()) { + if (p_info.Name == "Item") + continue; + + PropertyMetadata p_data = new PropertyMetadata (); + p_data.Info = p_info; + p_data.IsField = false; + props.Add (p_data); + } + + foreach (FieldInfo f_info in type.GetFields ()) { + PropertyMetadata p_data = new PropertyMetadata (); + p_data.Info = f_info; + p_data.IsField = true; + + props.Add (p_data); + } + + lock (type_properties_lock) { + try { + type_properties.Add (type, props); + } catch (ArgumentException) { + return; + } + } + } + + private static MethodInfo GetConvOp (Type t1, Type t2) + { + lock (conv_ops_lock) { + if (! conv_ops.ContainsKey (t1)) + conv_ops.Add (t1, new Dictionary ()); + } + + if (conv_ops[t1].ContainsKey (t2)) + return conv_ops[t1][t2]; + + MethodInfo op = t1.GetMethod ( + "op_Implicit", new Type[] { t2 }); + + lock (conv_ops_lock) { + try { + conv_ops[t1].Add (t2, op); + } catch (ArgumentException) { + return conv_ops[t1][t2]; + } + } + + return op; + } + + private static object ReadValue (Type inst_type, JsonReader reader) + { + reader.Read (); + + if (reader.Token == JsonToken.ArrayEnd) + return null; + + if (reader.Token == JsonToken.Null) { + + if (! inst_type.IsClass) + throw new JsonException (String.Format ( + "Can't assign null to an instance of type {0}", + inst_type)); + + return null; + } + + if (reader.Token == JsonToken.Double || + reader.Token == JsonToken.Int || + reader.Token == JsonToken.Long || + reader.Token == JsonToken.String || + reader.Token == JsonToken.Boolean) { + + Type json_type = reader.Value.GetType (); + + if (inst_type.IsAssignableFrom (json_type)) + return reader.Value; + + // If there's a custom importer that fits, use it + if (custom_importers_table.ContainsKey (json_type) && + custom_importers_table[json_type].ContainsKey ( + inst_type)) { + + ImporterFunc importer = + custom_importers_table[json_type][inst_type]; + + return importer (reader.Value); + } + + // Maybe there's a base importer that works + if (base_importers_table.ContainsKey (json_type) && + base_importers_table[json_type].ContainsKey ( + inst_type)) { + + ImporterFunc importer = + base_importers_table[json_type][inst_type]; + + return importer (reader.Value); + } + + // Maybe it's an enum + if (inst_type.IsEnum) + return Enum.ToObject (inst_type, reader.Value); + + // Try using an implicit conversion operator + MethodInfo conv_op = GetConvOp (inst_type, json_type); + + if (conv_op != null) + return conv_op.Invoke (null, + new object[] { reader.Value }); + + // No luck + throw new JsonException (String.Format ( + "Can't assign value '{0}' (type {1}) to type {2}", + reader.Value, json_type, inst_type)); + } + + object instance = null; + + if (reader.Token == JsonToken.ArrayStart) { + + AddArrayMetadata (inst_type); + ArrayMetadata t_data = array_metadata[inst_type]; + + if (! t_data.IsArray && ! t_data.IsList) + throw new JsonException (String.Format ( + "Type {0} can't act as an array", + inst_type)); + + IList list; + Type elem_type; + + if (! t_data.IsArray) { + list = (IList) Activator.CreateInstance (inst_type); + elem_type = t_data.ElementType; + } else { + list = new ArrayList (); + elem_type = inst_type.GetElementType (); + } + + while (true) { + object item = ReadValue (elem_type, reader); + if (reader.Token == JsonToken.ArrayEnd) + break; + + list.Add (item); + } + + if (t_data.IsArray) { + int n = list.Count; + instance = Array.CreateInstance (elem_type, n); + + for (int i = 0; i < n; i++) + ((Array) instance).SetValue (list[i], i); + } else + instance = list; + + } else if (reader.Token == JsonToken.ObjectStart) { + + AddObjectMetadata (inst_type); + ObjectMetadata t_data = object_metadata[inst_type]; + + instance = Activator.CreateInstance (inst_type); + + while (true) { + reader.Read (); + + if (reader.Token == JsonToken.ObjectEnd) + break; + + string property = (string) reader.Value; + + if (t_data.Properties.ContainsKey (property)) { + PropertyMetadata prop_data = + t_data.Properties[property]; + + if (prop_data.IsField) { + ((FieldInfo) prop_data.Info).SetValue ( + instance, ReadValue (prop_data.Type, reader)); + } else { + PropertyInfo p_info = + (PropertyInfo) prop_data.Info; + + if (p_info.CanWrite) + p_info.SetValue ( + instance, + ReadValue (prop_data.Type, reader), + null); + else + ReadValue (prop_data.Type, reader); + } + + } else { + if (! t_data.IsDictionary) + throw new JsonException (String.Format ( + "The type {0} doesn't have the " + + "property '{1}'", inst_type, property)); + + ((IDictionary) instance).Add ( + property, ReadValue ( + t_data.ElementType, reader)); + } + + } + + } + + return instance; + } + + private static IJsonWrapper ReadValue (WrapperFactory factory, + JsonReader reader) + { + reader.Read (); + + if (reader.Token == JsonToken.ArrayEnd || + reader.Token == JsonToken.Null) + return null; + + IJsonWrapper instance = factory (); + + if (reader.Token == JsonToken.String) { + instance.SetString ((string) reader.Value); + return instance; + } + + if (reader.Token == JsonToken.Double) { + instance.SetDouble ((double) reader.Value); + return instance; + } + + if (reader.Token == JsonToken.Int) { + instance.SetInt ((int) reader.Value); + return instance; + } + + if (reader.Token == JsonToken.Long) { + instance.SetLong ((long) reader.Value); + return instance; + } + + if (reader.Token == JsonToken.Boolean) { + instance.SetBoolean ((bool) reader.Value); + return instance; + } + + if (reader.Token == JsonToken.ArrayStart) { + instance.SetJsonType (JsonType.Array); + + while (true) { + IJsonWrapper item = ReadValue (factory, reader); + if (reader.Token == JsonToken.ArrayEnd) + break; + + ((IList) instance).Add (item); + } + } + else if (reader.Token == JsonToken.ObjectStart) { + instance.SetJsonType (JsonType.Object); + + while (true) { + reader.Read (); + + if (reader.Token == JsonToken.ObjectEnd) + break; + + string property = (string) reader.Value; + + ((IDictionary) instance)[property] = ReadValue ( + factory, reader); + } + + } + + return instance; + } + + private static void RegisterBaseExporters () + { + base_exporters_table[typeof (byte)] = + delegate (object obj, JsonWriter writer) { + writer.Write (Convert.ToInt32 ((byte) obj)); + }; + + base_exporters_table[typeof (char)] = + delegate (object obj, JsonWriter writer) { + writer.Write (Convert.ToString ((char) obj)); + }; + + base_exporters_table[typeof (DateTime)] = + delegate (object obj, JsonWriter writer) { + writer.Write (Convert.ToString ((DateTime) obj, + datetime_format)); + }; + + base_exporters_table[typeof (decimal)] = + delegate (object obj, JsonWriter writer) { + writer.Write ((decimal) obj); + }; + + base_exporters_table[typeof (sbyte)] = + delegate (object obj, JsonWriter writer) { + writer.Write (Convert.ToInt32 ((sbyte) obj)); + }; + + base_exporters_table[typeof (short)] = + delegate (object obj, JsonWriter writer) { + writer.Write (Convert.ToInt32 ((short) obj)); + }; + + base_exporters_table[typeof (ushort)] = + delegate (object obj, JsonWriter writer) { + writer.Write (Convert.ToInt32 ((ushort) obj)); + }; + + base_exporters_table[typeof (uint)] = + delegate (object obj, JsonWriter writer) { + writer.Write (Convert.ToUInt64 ((uint) obj)); + }; + + base_exporters_table[typeof (ulong)] = + delegate (object obj, JsonWriter writer) { + writer.Write ((ulong) obj); + }; + + base_exporters_table[typeof(float)] = + delegate(object obj, JsonWriter writer) + { + writer.Write((double)(float)obj); + }; + } + + private static void RegisterBaseImporters () + { + ImporterFunc importer; + + importer = delegate (object input) { + return Convert.ToByte ((int) input); + }; + RegisterImporter (base_importers_table, typeof (int), + typeof (byte), importer); + + importer = delegate (object input) { + return Convert.ToUInt64 ((int) input); + }; + RegisterImporter (base_importers_table, typeof (int), + typeof (ulong), importer); + + importer = delegate (object input) { + return Convert.ToSByte ((int) input); + }; + RegisterImporter (base_importers_table, typeof (int), + typeof (sbyte), importer); + + importer = delegate (object input) { + return Convert.ToInt16 ((int) input); + }; + RegisterImporter (base_importers_table, typeof (int), + typeof (short), importer); + + importer = delegate (object input) { + return Convert.ToUInt16 ((int) input); + }; + RegisterImporter (base_importers_table, typeof (int), + typeof (ushort), importer); + + importer = delegate (object input) { + return Convert.ToUInt32 ((int) input); + }; + RegisterImporter (base_importers_table, typeof (int), + typeof (uint), importer); + + importer = delegate (object input) { + return Convert.ToSingle ((int) input); + }; + RegisterImporter (base_importers_table, typeof (int), + typeof (float), importer); + + importer = delegate(object input) + { + return Convert.ToSingle((float)(double)input); + }; + RegisterImporter(base_importers_table, typeof(double), + typeof(float), importer); + + importer = delegate (object input) { + return Convert.ToDouble ((int) input); + }; + RegisterImporter (base_importers_table, typeof (int), + typeof (double), importer); + + importer = delegate (object input) { + return Convert.ToDecimal ((double) input); + }; + RegisterImporter (base_importers_table, typeof (double), + typeof (decimal), importer); + + + importer = delegate (object input) { + return Convert.ToUInt32 ((long) input); + }; + RegisterImporter (base_importers_table, typeof (long), + typeof (uint), importer); + + importer = delegate (object input) { + return Convert.ToChar ((string) input); + }; + RegisterImporter (base_importers_table, typeof (string), + typeof (char), importer); + + importer = delegate (object input) { + return Convert.ToDateTime ((string) input, datetime_format); + }; + RegisterImporter (base_importers_table, typeof (string), + typeof (DateTime), importer); + } + + private static void RegisterImporter ( + IDictionary> table, + Type json_type, Type value_type, ImporterFunc importer) + { + if (! table.ContainsKey (json_type)) + table.Add (json_type, new Dictionary ()); + + table[json_type][value_type] = importer; + } + + private static void WriteValue (object obj, JsonWriter writer, + bool writer_is_private, + int depth) + { + if (depth > max_nesting_depth) + throw new JsonException ( + String.Format ("Max allowed object depth reached while " + + "trying to export from type {0}", + obj.GetType ())); + + if (obj == null) { + writer.Write (null); + return; + } + + if (obj is IJsonWrapper) { + if (writer_is_private) + writer.TextWriter.Write (((IJsonWrapper) obj).ToJson ()); + else + ((IJsonWrapper) obj).ToJson (writer); + + return; + } + + if (obj is String) { + writer.Write ((string) obj); + return; + } + + if (obj is Double) { + writer.Write ((double) obj); + return; + } + + if (obj is Int32) { + writer.Write ((int) obj); + return; + } + + if (obj is Boolean) { + writer.Write ((bool) obj); + return; + } + + if (obj is Int64) { + writer.Write ((long) obj); + return; + } + + if (obj is Array) { + writer.WriteArrayStart (); + + foreach (object elem in (Array) obj) + WriteValue (elem, writer, writer_is_private, depth + 1); + + writer.WriteArrayEnd (); + + return; + } + + if (obj is IList) { + writer.WriteArrayStart (); + foreach (object elem in (IList) obj) + WriteValue (elem, writer, writer_is_private, depth + 1); + writer.WriteArrayEnd (); + + return; + } + + if (obj is IDictionary) { + writer.WriteObjectStart (); + foreach (DictionaryEntry entry in (IDictionary) obj) { + writer.WritePropertyName ((string) entry.Key); + WriteValue (entry.Value, writer, writer_is_private, + depth + 1); + } + writer.WriteObjectEnd (); + + return; + } + + Type obj_type = obj.GetType (); + + // See if there's a custom exporter for the object + if (custom_exporters_table.ContainsKey (obj_type)) { + ExporterFunc exporter = custom_exporters_table[obj_type]; + exporter (obj, writer); + + return; + } + + // If not, maybe there's a base exporter + if (base_exporters_table.ContainsKey (obj_type)) { + ExporterFunc exporter = base_exporters_table[obj_type]; + exporter (obj, writer); + + return; + } + + // Last option, let's see if it's an enum + if (obj is Enum) { + Type e_type = Enum.GetUnderlyingType (obj_type); + + if (e_type == typeof (long) + || e_type == typeof (uint) + || e_type == typeof (ulong)) + writer.Write ((ulong) obj); + else + writer.Write ((int) obj); + + return; + } + + // Okay, so it looks like the input should be exported as an + // object + AddTypeProperties (obj_type); + IList props = type_properties[obj_type]; + + writer.WriteObjectStart (); + foreach (PropertyMetadata p_data in props) { + if (p_data.IsField) { + writer.WritePropertyName (p_data.Info.Name); + WriteValue (((FieldInfo) p_data.Info).GetValue (obj), + writer, writer_is_private, depth + 1); + } + else { + PropertyInfo p_info = (PropertyInfo) p_data.Info; + + if (p_info.CanRead) { + writer.WritePropertyName (p_data.Info.Name); + WriteValue (p_info.GetValue (obj, null), + writer, writer_is_private, depth + 1); + } + } + } + writer.WriteObjectEnd (); + } + #endregion + + + public static string ToJson (object obj) + { + lock (static_writer_lock) { + static_writer.Reset (); + + WriteValue (obj, static_writer, true, 0); + + return static_writer.ToString (); + } + } + + public static void ToJson (object obj, JsonWriter writer) + { + WriteValue (obj, writer, false, 0); + } + + public static JsonData ToObject (JsonReader reader) + { + return (JsonData) ToWrapper ( + delegate { return new JsonData (); }, reader); + } + + public static JsonData ToObject (TextReader reader) + { + JsonReader json_reader = new JsonReader (reader); + + return (JsonData) ToWrapper ( + delegate { return new JsonData (); }, json_reader); + } + + public static JsonData ToObject (string json) + { + return (JsonData) ToWrapper ( + delegate { return new JsonData (); }, json); + } + + public static T ToObject (JsonReader reader) + { + return (T) ReadValue (typeof (T), reader); + } + + public static T ToObject (TextReader reader) + { + JsonReader json_reader = new JsonReader (reader); + + return (T) ReadValue (typeof (T), json_reader); + } + + public static T ToObject (string json) + { + JsonReader reader = new JsonReader (json); + + return (T) ReadValue (typeof (T), reader); + } + + public static IJsonWrapper ToWrapper (WrapperFactory factory, + JsonReader reader) + { + return ReadValue (factory, reader); + } + + public static IJsonWrapper ToWrapper (WrapperFactory factory, + string json) + { + JsonReader reader = new JsonReader (json); + + return ReadValue (factory, reader); + } + + public static void RegisterExporter (ExporterFunc exporter) + { + ExporterFunc exporter_wrapper = + delegate (object obj, JsonWriter writer) { + exporter ((T) obj, writer); + }; + + custom_exporters_table[typeof (T)] = exporter_wrapper; + } + + public static void RegisterImporter ( + ImporterFunc importer) + { + ImporterFunc importer_wrapper = + delegate (object input) { + return importer ((TJson) input); + }; + + RegisterImporter (custom_importers_table, typeof (TJson), + typeof (TValue), importer_wrapper); + } + + public static void UnregisterExporters () + { + custom_exporters_table.Clear (); + } + + public static void UnregisterImporters () + { + custom_importers_table.Clear (); + } + } +} diff --git a/cocosocket4unity/cocosocket4unity/JsonReader.cs b/cocosocket4unity/cocosocket4unity/JsonReader.cs new file mode 100644 index 0000000..bdbe24f --- /dev/null +++ b/cocosocket4unity/cocosocket4unity/JsonReader.cs @@ -0,0 +1,455 @@ +#region Header +/** + * JsonReader.cs + * Stream-like access to JSON text. + * + * The authors disclaim copyright to this source code. For more details, see + * the COPYING file included with this distribution. + **/ +#endregion + + +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; + + +namespace LitJson +{ + public enum JsonToken + { + None, + + ObjectStart, + PropertyName, + ObjectEnd, + + ArrayStart, + ArrayEnd, + + Int, + Long, + Double, + + String, + + Boolean, + Null + } + + + public class JsonReader + { + #region Fields + private static IDictionary> parse_table; + + private Stack automaton_stack; + private int current_input; + private int current_symbol; + private bool end_of_json; + private bool end_of_input; + private Lexer lexer; + private bool parser_in_string; + private bool parser_return; + private bool read_started; + private TextReader reader; + private bool reader_is_owned; + private object token_value; + private JsonToken token; + #endregion + + + #region Public Properties + public bool AllowComments { + get { return lexer.AllowComments; } + set { lexer.AllowComments = value; } + } + + public bool AllowSingleQuotedStrings { + get { return lexer.AllowSingleQuotedStrings; } + set { lexer.AllowSingleQuotedStrings = value; } + } + + public bool EndOfInput { + get { return end_of_input; } + } + + public bool EndOfJson { + get { return end_of_json; } + } + + public JsonToken Token { + get { return token; } + } + + public object Value { + get { return token_value; } + } + #endregion + + + #region Constructors + static JsonReader () + { + PopulateParseTable (); + } + + public JsonReader (string json_text) : + this (new StringReader (json_text), true) + { + } + + public JsonReader (TextReader reader) : + this (reader, false) + { + } + + private JsonReader (TextReader reader, bool owned) + { + if (reader == null) + throw new ArgumentNullException ("reader"); + + parser_in_string = false; + parser_return = false; + + read_started = false; + automaton_stack = new Stack (); + automaton_stack.Push ((int) ParserToken.End); + automaton_stack.Push ((int) ParserToken.Text); + + lexer = new Lexer (reader); + + end_of_input = false; + end_of_json = false; + + this.reader = reader; + reader_is_owned = owned; + } + #endregion + + + #region Static Methods + private static void PopulateParseTable () + { + parse_table = new Dictionary> (); + + TableAddRow (ParserToken.Array); + TableAddCol (ParserToken.Array, '[', + '[', + (int) ParserToken.ArrayPrime); + + TableAddRow (ParserToken.ArrayPrime); + TableAddCol (ParserToken.ArrayPrime, '"', + (int) ParserToken.Value, + + (int) ParserToken.ValueRest, + ']'); + TableAddCol (ParserToken.ArrayPrime, '[', + (int) ParserToken.Value, + (int) ParserToken.ValueRest, + ']'); + TableAddCol (ParserToken.ArrayPrime, ']', + ']'); + TableAddCol (ParserToken.ArrayPrime, '{', + (int) ParserToken.Value, + (int) ParserToken.ValueRest, + ']'); + TableAddCol (ParserToken.ArrayPrime, (int) ParserToken.Number, + (int) ParserToken.Value, + (int) ParserToken.ValueRest, + ']'); + TableAddCol (ParserToken.ArrayPrime, (int) ParserToken.True, + (int) ParserToken.Value, + (int) ParserToken.ValueRest, + ']'); + TableAddCol (ParserToken.ArrayPrime, (int) ParserToken.False, + (int) ParserToken.Value, + (int) ParserToken.ValueRest, + ']'); + TableAddCol (ParserToken.ArrayPrime, (int) ParserToken.Null, + (int) ParserToken.Value, + (int) ParserToken.ValueRest, + ']'); + + TableAddRow (ParserToken.Object); + TableAddCol (ParserToken.Object, '{', + '{', + (int) ParserToken.ObjectPrime); + + TableAddRow (ParserToken.ObjectPrime); + TableAddCol (ParserToken.ObjectPrime, '"', + (int) ParserToken.Pair, + (int) ParserToken.PairRest, + '}'); + TableAddCol (ParserToken.ObjectPrime, '}', + '}'); + + TableAddRow (ParserToken.Pair); + TableAddCol (ParserToken.Pair, '"', + (int) ParserToken.String, + ':', + (int) ParserToken.Value); + + TableAddRow (ParserToken.PairRest); + TableAddCol (ParserToken.PairRest, ',', + ',', + (int) ParserToken.Pair, + (int) ParserToken.PairRest); + TableAddCol (ParserToken.PairRest, '}', + (int) ParserToken.Epsilon); + + TableAddRow (ParserToken.String); + TableAddCol (ParserToken.String, '"', + '"', + (int) ParserToken.CharSeq, + '"'); + + TableAddRow (ParserToken.Text); + TableAddCol (ParserToken.Text, '[', + (int) ParserToken.Array); + TableAddCol (ParserToken.Text, '{', + (int) ParserToken.Object); + + TableAddRow (ParserToken.Value); + TableAddCol (ParserToken.Value, '"', + (int) ParserToken.String); + TableAddCol (ParserToken.Value, '[', + (int) ParserToken.Array); + TableAddCol (ParserToken.Value, '{', + (int) ParserToken.Object); + TableAddCol (ParserToken.Value, (int) ParserToken.Number, + (int) ParserToken.Number); + TableAddCol (ParserToken.Value, (int) ParserToken.True, + (int) ParserToken.True); + TableAddCol (ParserToken.Value, (int) ParserToken.False, + (int) ParserToken.False); + TableAddCol (ParserToken.Value, (int) ParserToken.Null, + (int) ParserToken.Null); + + TableAddRow (ParserToken.ValueRest); + TableAddCol (ParserToken.ValueRest, ',', + ',', + (int) ParserToken.Value, + (int) ParserToken.ValueRest); + TableAddCol (ParserToken.ValueRest, ']', + (int) ParserToken.Epsilon); + } + + private static void TableAddCol (ParserToken row, int col, + params int[] symbols) + { + parse_table[(int) row].Add (col, symbols); + } + + private static void TableAddRow (ParserToken rule) + { + parse_table.Add ((int) rule, new Dictionary ()); + } + #endregion + + + #region Private Methods + private void ProcessNumber (string number) + { + if (number.IndexOf ('.') != -1 || + number.IndexOf ('e') != -1 || + number.IndexOf ('E') != -1) { + + double n_double; + if (Double.TryParse (number, out n_double)) { + token = JsonToken.Double; + token_value = n_double; + + return; + } + } + + int n_int32; + if (Int32.TryParse (number, out n_int32)) { + token = JsonToken.Int; + token_value = n_int32; + + return; + } + + long n_int64; + if (Int64.TryParse (number, out n_int64)) { + token = JsonToken.Long; + token_value = n_int64; + + return; + } + + // Shouldn't happen, but just in case, return something + token = JsonToken.Int; + token_value = 0; + } + + private void ProcessSymbol () + { + if (current_symbol == '[') { + token = JsonToken.ArrayStart; + parser_return = true; + + } else if (current_symbol == ']') { + token = JsonToken.ArrayEnd; + parser_return = true; + + } else if (current_symbol == '{') { + token = JsonToken.ObjectStart; + parser_return = true; + + } else if (current_symbol == '}') { + token = JsonToken.ObjectEnd; + parser_return = true; + + } else if (current_symbol == '"') { + if (parser_in_string) { + parser_in_string = false; + + parser_return = true; + + } else { + if (token == JsonToken.None) + token = JsonToken.String; + + parser_in_string = true; + } + + } else if (current_symbol == (int) ParserToken.CharSeq) { + token_value = lexer.StringValue; + + } else if (current_symbol == (int) ParserToken.False) { + token = JsonToken.Boolean; + token_value = false; + parser_return = true; + + } else if (current_symbol == (int) ParserToken.Null) { + token = JsonToken.Null; + parser_return = true; + + } else if (current_symbol == (int) ParserToken.Number) { + ProcessNumber (lexer.StringValue); + + parser_return = true; + + } else if (current_symbol == (int) ParserToken.Pair) { + token = JsonToken.PropertyName; + + } else if (current_symbol == (int) ParserToken.True) { + token = JsonToken.Boolean; + token_value = true; + parser_return = true; + + } + } + + private bool ReadToken () + { + if (end_of_input) + return false; + + lexer.NextToken (); + + if (lexer.EndOfInput) { + Close (); + + return false; + } + + current_input = lexer.Token; + + return true; + } + #endregion + + + public void Close () + { + if (end_of_input) + return; + + end_of_input = true; + end_of_json = true; + + if (reader_is_owned) + reader.Close (); + + reader = null; + } + + public bool Read () + { + if (end_of_input) + return false; + + if (end_of_json) { + end_of_json = false; + automaton_stack.Clear (); + automaton_stack.Push ((int) ParserToken.End); + automaton_stack.Push ((int) ParserToken.Text); + } + + parser_in_string = false; + parser_return = false; + + token = JsonToken.None; + token_value = null; + + if (! read_started) { + read_started = true; + + if (! ReadToken ()) + return false; + } + + + int[] entry_symbols; + + while (true) { + if (parser_return) { + if (automaton_stack.Peek () == (int) ParserToken.End) + end_of_json = true; + + return true; + } + + current_symbol = automaton_stack.Pop (); + + ProcessSymbol (); + + if (current_symbol == current_input) { + if (! ReadToken ()) { + if (automaton_stack.Peek () != (int) ParserToken.End) + throw new JsonException ( + "Input doesn't evaluate to proper JSON text"); + + if (parser_return) + return true; + + return false; + } + + continue; + } + + try { + + entry_symbols = + parse_table[current_symbol][current_input]; + + } catch (KeyNotFoundException e) { + throw new JsonException ((ParserToken) current_input, e); + } + + if (entry_symbols[0] == (int) ParserToken.Epsilon) + continue; + + for (int i = entry_symbols.Length - 1; i >= 0; i--) + automaton_stack.Push (entry_symbols[i]); + } + } + + } +} diff --git a/cocosocket4unity/cocosocket4unity/JsonWriter.cs b/cocosocket4unity/cocosocket4unity/JsonWriter.cs new file mode 100644 index 0000000..da3c79a --- /dev/null +++ b/cocosocket4unity/cocosocket4unity/JsonWriter.cs @@ -0,0 +1,462 @@ +#region Header +/** + * JsonWriter.cs + * Stream-like facility to output JSON text. + * + * The authors disclaim copyright to this source code. For more details, see + * the COPYING file included with this distribution. + **/ +#endregion + + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Text; + + +namespace LitJson +{ + internal enum Condition + { + InArray, + InObject, + NotAProperty, + Property, + Value + } + + internal class WriterContext + { + public int Count; + public bool InArray; + public bool InObject; + public bool ExpectingValue; + public int Padding; + } + + public class JsonWriter + { + #region Fields + private static NumberFormatInfo number_format; + + private WriterContext context; + private Stack ctx_stack; + private bool has_reached_end; + private char[] hex_seq; + private int indentation; + private int indent_value; + private StringBuilder inst_string_builder; + private bool pretty_print; + private bool validate; + private TextWriter writer; + #endregion + + + #region Properties + public int IndentValue { + get { return indent_value; } + set { + indentation = (indentation / indent_value) * value; + indent_value = value; + } + } + + public bool PrettyPrint { + get { return pretty_print; } + set { pretty_print = value; } + } + + public TextWriter TextWriter { + get { return writer; } + } + + public bool Validate { + get { return validate; } + set { validate = value; } + } + #endregion + + + #region Constructors + static JsonWriter () + { + number_format = NumberFormatInfo.InvariantInfo; + } + + public JsonWriter () + { + inst_string_builder = new StringBuilder (); + writer = new StringWriter (inst_string_builder); + + Init (); + } + + public JsonWriter (StringBuilder sb) : + this (new StringWriter (sb)) + { + } + + public JsonWriter (TextWriter writer) + { + if (writer == null) + throw new ArgumentNullException ("writer"); + + this.writer = writer; + + Init (); + } + #endregion + + + #region Private Methods + private void DoValidation (Condition cond) + { + if (! context.ExpectingValue) + context.Count++; + + if (! validate) + return; + + if (has_reached_end) + throw new JsonException ( + "A complete JSON symbol has already been written"); + + switch (cond) { + case Condition.InArray: + if (! context.InArray) + throw new JsonException ( + "Can't close an array here"); + break; + + case Condition.InObject: + if (! context.InObject || context.ExpectingValue) + throw new JsonException ( + "Can't close an object here"); + break; + + case Condition.NotAProperty: + if (context.InObject && ! context.ExpectingValue) + throw new JsonException ( + "Expected a property"); + break; + + case Condition.Property: + if (! context.InObject || context.ExpectingValue) + throw new JsonException ( + "Can't add a property here"); + break; + + case Condition.Value: + if (! context.InArray && + (! context.InObject || ! context.ExpectingValue)) + throw new JsonException ( + "Can't add a value here"); + + break; + } + } + + private void Init () + { + has_reached_end = false; + hex_seq = new char[4]; + indentation = 0; + indent_value = 4; + pretty_print = false; + validate = true; + + ctx_stack = new Stack (); + context = new WriterContext (); + ctx_stack.Push (context); + } + + private static void IntToHex (int n, char[] hex) + { + int num; + + for (int i = 0; i < 4; i++) { + num = n % 16; + + if (num < 10) + hex[3 - i] = (char) ('0' + num); + else + hex[3 - i] = (char) ('A' + (num - 10)); + + n >>= 4; + } + } + + private void Indent () + { + if (pretty_print) + indentation += indent_value; + } + + + private void Put (string str) + { + if (pretty_print && ! context.ExpectingValue) + for (int i = 0; i < indentation; i++) + writer.Write (' '); + + writer.Write (str); + } + + private void PutNewline () + { + PutNewline (true); + } + + private void PutNewline (bool add_comma) + { + if (add_comma && ! context.ExpectingValue && + context.Count > 1) + writer.Write (','); + + if (pretty_print && ! context.ExpectingValue) + writer.Write ('\n'); + } + + private void PutString (string str) + { + Put (String.Empty); + + writer.Write ('"'); + + int n = str.Length; + for (int i = 0; i < n; i++) { + switch (str[i]) { + case '\n': + writer.Write ("\\n"); + continue; + + case '\r': + writer.Write ("\\r"); + continue; + + case '\t': + writer.Write ("\\t"); + continue; + + case '"': + case '\\': + writer.Write ('\\'); + writer.Write (str[i]); + continue; + + case '\f': + writer.Write ("\\f"); + continue; + + case '\b': + writer.Write ("\\b"); + continue; + } + + // if ((int) str[i] >= 32 && (int) str[i] <= 126) { + writer.Write (str[i]); + continue; + // } + + // Default, turn into a \uXXXX sequence + //IntToHex ((int) str[i], hex_seq); + //writer.Write ("\\u"); + //writer.Write (hex_seq); + } + + writer.Write ('"'); + } + + private void Unindent () + { + if (pretty_print) + indentation -= indent_value; + } + #endregion + + + public override string ToString () + { + if (inst_string_builder == null) + return String.Empty; + + return inst_string_builder.ToString (); + } + + public void Reset () + { + has_reached_end = false; + + ctx_stack.Clear (); + context = new WriterContext (); + ctx_stack.Push (context); + + if (inst_string_builder != null) + inst_string_builder.Remove (0, inst_string_builder.Length); + } + + public void Write (bool boolean) + { + DoValidation (Condition.Value); + PutNewline (); + + Put (boolean ? "true" : "false"); + + context.ExpectingValue = false; + } + + public void Write (decimal number) + { + DoValidation (Condition.Value); + PutNewline (); + + Put (Convert.ToString (number, number_format)); + + context.ExpectingValue = false; + } + + public void Write (double number) + { + DoValidation (Condition.Value); + PutNewline (); + + string str = Convert.ToString (number, number_format); + Put (str); + + if (str.IndexOf ('.') == -1 && + str.IndexOf ('E') == -1) + writer.Write (".0"); + + context.ExpectingValue = false; + } + + public void Write (int number) + { + DoValidation (Condition.Value); + PutNewline (); + + Put (Convert.ToString (number, number_format)); + + context.ExpectingValue = false; + } + + public void Write (long number) + { + DoValidation (Condition.Value); + PutNewline (); + + Put (Convert.ToString (number, number_format)); + + context.ExpectingValue = false; + } + + public void Write (string str) + { + DoValidation (Condition.Value); + PutNewline (); + + if (str == null) + Put ("null"); + else + PutString (str); + + context.ExpectingValue = false; + } + + public void Write (ulong number) + { + DoValidation (Condition.Value); + PutNewline (); + + Put (Convert.ToString (number, number_format)); + + context.ExpectingValue = false; + } + + public void WriteArrayEnd () + { + DoValidation (Condition.InArray); + PutNewline (false); + + ctx_stack.Pop (); + if (ctx_stack.Count == 1) + has_reached_end = true; + else { + context = ctx_stack.Peek (); + context.ExpectingValue = false; + } + + Unindent (); + Put ("]"); + } + + public void WriteArrayStart () + { + DoValidation (Condition.NotAProperty); + PutNewline (); + + Put ("["); + + context = new WriterContext (); + context.InArray = true; + ctx_stack.Push (context); + + Indent (); + } + + public void WriteObjectEnd () + { + DoValidation (Condition.InObject); + PutNewline (false); + + ctx_stack.Pop (); + if (ctx_stack.Count == 1) + has_reached_end = true; + else { + context = ctx_stack.Peek (); + context.ExpectingValue = false; + } + + Unindent (); + Put ("}"); + } + + public void WriteObjectStart () + { + DoValidation (Condition.NotAProperty); + PutNewline (); + + Put ("{"); + + context = new WriterContext (); + context.InObject = true; + ctx_stack.Push (context); + + Indent (); + } + + public void WritePropertyName (string property_name) + { + DoValidation (Condition.Property); + PutNewline (); + + PutString (property_name); + + if (pretty_print) { + if (property_name.Length > context.Padding) + context.Padding = property_name.Length; + + for (int i = context.Padding - property_name.Length; + i >= 0; i--) + writer.Write (' '); + + writer.Write (": "); + } else + writer.Write (':'); + + context.ExpectingValue = true; + } + } +} diff --git a/cocosocket4unity/cocosocket4unity/LVProtocal.cs b/cocosocket4unity/cocosocket4unity/LVProtocal.cs new file mode 100644 index 0000000..312bb23 --- /dev/null +++ b/cocosocket4unity/cocosocket4unity/LVProtocal.cs @@ -0,0 +1,52 @@ +锘縰sing System; + +namespace cocosocket4unity +{ + public class LVProtocal : Protocal + { + private int status; + private int h; + private int l; + private short len; + private ByteBuf frame; + + public LVProtocal () + { + + } + /** + * 鍒嗗抚閫昏緫 + * + **/ + public ByteBuf TranslateFrame(ByteBuf src) + { + while (src.ReadableBytes() > 0) + { + switch (status) + { + case 0: + h = src.ReadByte(); + status = 1; + break; + case 1: + l = src.ReadByte(); + len = (short)(((h << 8)&0x0000ff00) | (l)); + frame = new ByteBuf(len + 2); + frame.WriteShort(len); + status = 2; + break; + case 2: + frame.WriteBytes(src); + if (frame.WritableBytes() <= 0) + { + status = 0; + return frame; + } + break; + } + } + return null; + } + } +} + diff --git a/cocosocket4unity/cocosocket4unity/Lexer.cs b/cocosocket4unity/cocosocket4unity/Lexer.cs new file mode 100644 index 0000000..2ea484b --- /dev/null +++ b/cocosocket4unity/cocosocket4unity/Lexer.cs @@ -0,0 +1,910 @@ +#region Header +/** + * Lexer.cs + * JSON lexer implementation based on a finite state machine. + * + * The authors disclaim copyright to this source code. For more details, see + * the COPYING file included with this distribution. + **/ +#endregion + + +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; + + +namespace LitJson +{ + internal class FsmContext + { + public bool Return; + public int NextState; + public Lexer L; + public int StateStack; + } + + + internal class Lexer + { + #region Fields + private delegate bool StateHandler (FsmContext ctx); + + private static int[] fsm_return_table; + private static StateHandler[] fsm_handler_table; + + private bool allow_comments; + private bool allow_single_quoted_strings; + private bool end_of_input; + private FsmContext fsm_context; + private int input_buffer; + private int input_char; + private TextReader reader; + private int state; + private StringBuilder string_buffer; + private string string_value; + private int token; + private int unichar; + #endregion + + + #region Properties + public bool AllowComments { + get { return allow_comments; } + set { allow_comments = value; } + } + + public bool AllowSingleQuotedStrings { + get { return allow_single_quoted_strings; } + set { allow_single_quoted_strings = value; } + } + + public bool EndOfInput { + get { return end_of_input; } + } + + public int Token { + get { return token; } + } + + public string StringValue { + get { return string_value; } + } + #endregion + + + #region Constructors + static Lexer () + { + PopulateFsmTables (); + } + + public Lexer (TextReader reader) + { + allow_comments = true; + allow_single_quoted_strings = true; + + input_buffer = 0; + string_buffer = new StringBuilder (128); + state = 1; + end_of_input = false; + this.reader = reader; + + fsm_context = new FsmContext (); + fsm_context.L = this; + } + #endregion + + + #region Static Methods + private static int HexValue (int digit) + { + switch (digit) { + case 'a': + case 'A': + return 10; + + case 'b': + case 'B': + return 11; + + case 'c': + case 'C': + return 12; + + case 'd': + case 'D': + return 13; + + case 'e': + case 'E': + return 14; + + case 'f': + case 'F': + return 15; + + default: + return digit - '0'; + } + } + + private static void PopulateFsmTables () + { + fsm_handler_table = new StateHandler[28] { + State1, + State2, + State3, + State4, + State5, + State6, + State7, + State8, + State9, + State10, + State11, + State12, + State13, + State14, + State15, + State16, + State17, + State18, + State19, + State20, + State21, + State22, + State23, + State24, + State25, + State26, + State27, + State28 + }; + + fsm_return_table = new int[28] { + (int) ParserToken.Char, + 0, + (int) ParserToken.Number, + (int) ParserToken.Number, + 0, + (int) ParserToken.Number, + 0, + (int) ParserToken.Number, + 0, + 0, + (int) ParserToken.True, + 0, + 0, + 0, + (int) ParserToken.False, + 0, + 0, + (int) ParserToken.Null, + (int) ParserToken.CharSeq, + (int) ParserToken.Char, + 0, + 0, + (int) ParserToken.CharSeq, + (int) ParserToken.Char, + 0, + 0, + 0, + 0 + }; + } + + private static char ProcessEscChar (int esc_char) + { + switch (esc_char) { + case '"': + case '\'': + case '\\': + case '/': + return Convert.ToChar (esc_char); + + case 'n': + return '\n'; + + case 't': + return '\t'; + + case 'r': + return '\r'; + + case 'b': + return '\b'; + + case 'f': + return '\f'; + + default: + // Unreachable + return '?'; + } + } + + private static bool State1 (FsmContext ctx) + { + while (ctx.L.GetChar ()) { + if (ctx.L.input_char == ' ' || + ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') + continue; + + if (ctx.L.input_char >= '1' && ctx.L.input_char <= '9') { + ctx.L.string_buffer.Append ((char) ctx.L.input_char); + ctx.NextState = 3; + return true; + } + + switch (ctx.L.input_char) { + case '"': + ctx.NextState = 19; + ctx.Return = true; + return true; + + case ',': + case ':': + case '[': + case ']': + case '{': + case '}': + ctx.NextState = 1; + ctx.Return = true; + return true; + + case '-': + ctx.L.string_buffer.Append ((char) ctx.L.input_char); + ctx.NextState = 2; + return true; + + case '0': + ctx.L.string_buffer.Append ((char) ctx.L.input_char); + ctx.NextState = 4; + return true; + + case 'f': + ctx.NextState = 12; + return true; + + case 'n': + ctx.NextState = 16; + return true; + + case 't': + ctx.NextState = 9; + return true; + + case '\'': + if (! ctx.L.allow_single_quoted_strings) + return false; + + ctx.L.input_char = '"'; + ctx.NextState = 23; + ctx.Return = true; + return true; + + case '/': + if (! ctx.L.allow_comments) + return false; + + ctx.NextState = 25; + return true; + + default: + return false; + } + } + + return true; + } + + private static bool State2 (FsmContext ctx) + { + ctx.L.GetChar (); + + if (ctx.L.input_char >= '1' && ctx.L.input_char<= '9') { + ctx.L.string_buffer.Append ((char) ctx.L.input_char); + ctx.NextState = 3; + return true; + } + + switch (ctx.L.input_char) { + case '0': + ctx.L.string_buffer.Append ((char) ctx.L.input_char); + ctx.NextState = 4; + return true; + + default: + return false; + } + } + + private static bool State3 (FsmContext ctx) + { + while (ctx.L.GetChar ()) { + if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') { + ctx.L.string_buffer.Append ((char) ctx.L.input_char); + continue; + } + + if (ctx.L.input_char == ' ' || + ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') { + ctx.Return = true; + ctx.NextState = 1; + return true; + } + + switch (ctx.L.input_char) { + case ',': + case ']': + case '}': + ctx.L.UngetChar (); + ctx.Return = true; + ctx.NextState = 1; + return true; + + case '.': + ctx.L.string_buffer.Append ((char) ctx.L.input_char); + ctx.NextState = 5; + return true; + + case 'e': + case 'E': + ctx.L.string_buffer.Append ((char) ctx.L.input_char); + ctx.NextState = 7; + return true; + + default: + return false; + } + } + return true; + } + + private static bool State4 (FsmContext ctx) + { + ctx.L.GetChar (); + + if (ctx.L.input_char == ' ' || + ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') { + ctx.Return = true; + ctx.NextState = 1; + return true; + } + + switch (ctx.L.input_char) { + case ',': + case ']': + case '}': + ctx.L.UngetChar (); + ctx.Return = true; + ctx.NextState = 1; + return true; + + case '.': + ctx.L.string_buffer.Append ((char) ctx.L.input_char); + ctx.NextState = 5; + return true; + + case 'e': + case 'E': + ctx.L.string_buffer.Append ((char) ctx.L.input_char); + ctx.NextState = 7; + return true; + + default: + return false; + } + } + + private static bool State5 (FsmContext ctx) + { + ctx.L.GetChar (); + + if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') { + ctx.L.string_buffer.Append ((char) ctx.L.input_char); + ctx.NextState = 6; + return true; + } + + return false; + } + + private static bool State6 (FsmContext ctx) + { + while (ctx.L.GetChar ()) { + if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') { + ctx.L.string_buffer.Append ((char) ctx.L.input_char); + continue; + } + + if (ctx.L.input_char == ' ' || + ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') { + ctx.Return = true; + ctx.NextState = 1; + return true; + } + + switch (ctx.L.input_char) { + case ',': + case ']': + case '}': + ctx.L.UngetChar (); + ctx.Return = true; + ctx.NextState = 1; + return true; + + case 'e': + case 'E': + ctx.L.string_buffer.Append ((char) ctx.L.input_char); + ctx.NextState = 7; + return true; + + default: + return false; + } + } + + return true; + } + + private static bool State7 (FsmContext ctx) + { + ctx.L.GetChar (); + + if (ctx.L.input_char >= '0' && ctx.L.input_char<= '9') { + ctx.L.string_buffer.Append ((char) ctx.L.input_char); + ctx.NextState = 8; + return true; + } + + switch (ctx.L.input_char) { + case '+': + case '-': + ctx.L.string_buffer.Append ((char) ctx.L.input_char); + ctx.NextState = 8; + return true; + + default: + return false; + } + } + + private static bool State8 (FsmContext ctx) + { + while (ctx.L.GetChar ()) { + if (ctx.L.input_char >= '0' && ctx.L.input_char<= '9') { + ctx.L.string_buffer.Append ((char) ctx.L.input_char); + continue; + } + + if (ctx.L.input_char == ' ' || + ctx.L.input_char >= '\t' && ctx.L.input_char<= '\r') { + ctx.Return = true; + ctx.NextState = 1; + return true; + } + + switch (ctx.L.input_char) { + case ',': + case ']': + case '}': + ctx.L.UngetChar (); + ctx.Return = true; + ctx.NextState = 1; + return true; + + default: + return false; + } + } + + return true; + } + + private static bool State9 (FsmContext ctx) + { + ctx.L.GetChar (); + + switch (ctx.L.input_char) { + case 'r': + ctx.NextState = 10; + return true; + + default: + return false; + } + } + + private static bool State10 (FsmContext ctx) + { + ctx.L.GetChar (); + + switch (ctx.L.input_char) { + case 'u': + ctx.NextState = 11; + return true; + + default: + return false; + } + } + + private static bool State11 (FsmContext ctx) + { + ctx.L.GetChar (); + + switch (ctx.L.input_char) { + case 'e': + ctx.Return = true; + ctx.NextState = 1; + return true; + + default: + return false; + } + } + + private static bool State12 (FsmContext ctx) + { + ctx.L.GetChar (); + + switch (ctx.L.input_char) { + case 'a': + ctx.NextState = 13; + return true; + + default: + return false; + } + } + + private static bool State13 (FsmContext ctx) + { + ctx.L.GetChar (); + + switch (ctx.L.input_char) { + case 'l': + ctx.NextState = 14; + return true; + + default: + return false; + } + } + + private static bool State14 (FsmContext ctx) + { + ctx.L.GetChar (); + + switch (ctx.L.input_char) { + case 's': + ctx.NextState = 15; + return true; + + default: + return false; + } + } + + private static bool State15 (FsmContext ctx) + { + ctx.L.GetChar (); + + switch (ctx.L.input_char) { + case 'e': + ctx.Return = true; + ctx.NextState = 1; + return true; + + default: + return false; + } + } + + private static bool State16 (FsmContext ctx) + { + ctx.L.GetChar (); + + switch (ctx.L.input_char) { + case 'u': + ctx.NextState = 17; + return true; + + default: + return false; + } + } + + private static bool State17 (FsmContext ctx) + { + ctx.L.GetChar (); + + switch (ctx.L.input_char) { + case 'l': + ctx.NextState = 18; + return true; + + default: + return false; + } + } + + private static bool State18 (FsmContext ctx) + { + ctx.L.GetChar (); + + switch (ctx.L.input_char) { + case 'l': + ctx.Return = true; + ctx.NextState = 1; + return true; + + default: + return false; + } + } + + private static bool State19 (FsmContext ctx) + { + while (ctx.L.GetChar ()) { + switch (ctx.L.input_char) { + case '"': + ctx.L.UngetChar (); + ctx.Return = true; + ctx.NextState = 20; + return true; + + case '\\': + ctx.StateStack = 19; + ctx.NextState = 21; + return true; + + default: + ctx.L.string_buffer.Append ((char) ctx.L.input_char); + continue; + } + } + + return true; + } + + private static bool State20 (FsmContext ctx) + { + ctx.L.GetChar (); + + switch (ctx.L.input_char) { + case '"': + ctx.Return = true; + ctx.NextState = 1; + return true; + + default: + return false; + } + } + + private static bool State21 (FsmContext ctx) + { + ctx.L.GetChar (); + + switch (ctx.L.input_char) { + case 'u': + ctx.NextState = 22; + return true; + + case '"': + case '\'': + case '/': + case '\\': + case 'b': + case 'f': + case 'n': + case 'r': + case 't': + ctx.L.string_buffer.Append ( + ProcessEscChar (ctx.L.input_char)); + ctx.NextState = ctx.StateStack; + return true; + + default: + return false; + } + } + + private static bool State22 (FsmContext ctx) + { + int counter = 0; + int mult = 4096; + + ctx.L.unichar = 0; + + while (ctx.L.GetChar ()) { + + if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9' || + ctx.L.input_char >= 'A' && ctx.L.input_char <= 'F' || + ctx.L.input_char >= 'a' && ctx.L.input_char <= 'f') { + + ctx.L.unichar += HexValue (ctx.L.input_char) * mult; + + counter++; + mult /= 16; + + if (counter == 4) { + ctx.L.string_buffer.Append ( + Convert.ToChar (ctx.L.unichar)); + ctx.NextState = ctx.StateStack; + return true; + } + + continue; + } + + return false; + } + + return true; + } + + private static bool State23 (FsmContext ctx) + { + while (ctx.L.GetChar ()) { + switch (ctx.L.input_char) { + case '\'': + ctx.L.UngetChar (); + ctx.Return = true; + ctx.NextState = 24; + return true; + + case '\\': + ctx.StateStack = 23; + ctx.NextState = 21; + return true; + + default: + ctx.L.string_buffer.Append ((char) ctx.L.input_char); + continue; + } + } + + return true; + } + + private static bool State24 (FsmContext ctx) + { + ctx.L.GetChar (); + + switch (ctx.L.input_char) { + case '\'': + ctx.L.input_char = '"'; + ctx.Return = true; + ctx.NextState = 1; + return true; + + default: + return false; + } + } + + private static bool State25 (FsmContext ctx) + { + ctx.L.GetChar (); + + switch (ctx.L.input_char) { + case '*': + ctx.NextState = 27; + return true; + + case '/': + ctx.NextState = 26; + return true; + + default: + return false; + } + } + + private static bool State26 (FsmContext ctx) + { + while (ctx.L.GetChar ()) { + if (ctx.L.input_char == '\n') { + ctx.NextState = 1; + return true; + } + } + + return true; + } + + private static bool State27 (FsmContext ctx) + { + while (ctx.L.GetChar ()) { + if (ctx.L.input_char == '*') { + ctx.NextState = 28; + return true; + } + } + + return true; + } + + private static bool State28 (FsmContext ctx) + { + while (ctx.L.GetChar ()) { + if (ctx.L.input_char == '*') + continue; + + if (ctx.L.input_char == '/') { + ctx.NextState = 1; + return true; + } + + ctx.NextState = 27; + return true; + } + + return true; + } + #endregion + + + private bool GetChar () + { + if ((input_char = NextChar ()) != -1) + return true; + + end_of_input = true; + return false; + } + + private int NextChar () + { + if (input_buffer != 0) { + int tmp = input_buffer; + input_buffer = 0; + + return tmp; + } + + return reader.Read (); + } + + public bool NextToken () + { + StateHandler handler; + fsm_context.Return = false; + + while (true) { + handler = fsm_handler_table[state - 1]; + + if (! handler (fsm_context)) + throw new JsonException (input_char); + + if (end_of_input) + return false; + + if (fsm_context.Return) { + string_value = string_buffer.ToString (); + string_buffer.Remove (0, string_buffer.Length); + token = fsm_return_table[state - 1]; + + if (token == (int) ParserToken.Char) + token = input_char; + + state = fsm_context.NextState; + + return true; + } + + state = fsm_context.NextState; + } + } + + private void UngetChar () + { + input_buffer = input_char; + } + } +} diff --git a/cocosocket4unity/cocosocket4unity/Main.cs b/cocosocket4unity/cocosocket4unity/Main.cs new file mode 100644 index 0000000..222173d --- /dev/null +++ b/cocosocket4unity/cocosocket4unity/Main.cs @@ -0,0 +1,24 @@ +using System; +using LitJson; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Net.Sockets; +using System.Net; +namespace cocosocket4unity +{ + class MainClass + { + public static void Main (string[] args) + { + + SocketListner listner = new TestListner (); + USocket us = new USocket (); + us.setLister (listner); + Protocal p = new LVProtocal (); + us.setProtocal (p); + us.Connect ("10.0.110.184", 3210); + Console.Read(); + } + } +} diff --git a/cocosocket4unity/cocosocket4unity/ParserToken.cs b/cocosocket4unity/cocosocket4unity/ParserToken.cs new file mode 100644 index 0000000..c5a9a43 --- /dev/null +++ b/cocosocket4unity/cocosocket4unity/ParserToken.cs @@ -0,0 +1,44 @@ +#region Header +/** + * ParserToken.cs + * Internal representation of the tokens used by the lexer and the parser. + * + * The authors disclaim copyright to this source code. For more details, see + * the COPYING file included with this distribution. + **/ +#endregion + + +namespace LitJson +{ + internal enum ParserToken + { + // Lexer tokens + None = System.Char.MaxValue + 1, + Number, + True, + False, + Null, + CharSeq, + // Single char + Char, + + // Parser Rules + Text, + Object, + ObjectPrime, + Pair, + PairRest, + Array, + ArrayPrime, + Value, + ValueRest, + String, + + // End of input + End, + + // The empty rule + Epsilon + } +} diff --git a/cocosocket4unity/cocosocket4unity/Protocal.cs b/cocosocket4unity/cocosocket4unity/Protocal.cs new file mode 100644 index 0000000..91cc31a --- /dev/null +++ b/cocosocket4unity/cocosocket4unity/Protocal.cs @@ -0,0 +1,10 @@ +锘縰sing System; + +namespace cocosocket4unity +{ + public interface Protocal + { + ByteBuf TranslateFrame (ByteBuf src); + } +} + diff --git a/cocosocket4unity/cocosocket4unity/SocketListner.cs b/cocosocket4unity/cocosocket4unity/SocketListner.cs new file mode 100644 index 0000000..079b0fe --- /dev/null +++ b/cocosocket4unity/cocosocket4unity/SocketListner.cs @@ -0,0 +1,14 @@ +锘縰sing System; + +namespace cocosocket4unity +{ + public abstract class SocketListner + { + abstract public void OnMessage(USocket us,ByteBuf bb); + abstract public void OnClose(USocket us,bool fromRemote); + abstract public void OnIdle(USocket us); + abstract public void OnOpen(USocket us); + abstract public void OnError(USocket us,string err); + } +} + diff --git a/cocosocket4unity/cocosocket4unity/TestListner.cs b/cocosocket4unity/cocosocket4unity/TestListner.cs new file mode 100644 index 0000000..720fdda --- /dev/null +++ b/cocosocket4unity/cocosocket4unity/TestListner.cs @@ -0,0 +1,51 @@ +锘縰sing System; +using LitJson; + +namespace cocosocket4unity +{ + public class TestListner : SocketListner + { + public TestListner () + { + } + + public override void OnMessage(USocket us,ByteBuf bb) + { + Console.WriteLine ("鏀跺埌鏁版嵁:"); + bb.ReaderIndex (2); + string s=bb.ReadUTF8 (); + Console.WriteLine (s); + bb.ReaderIndex (0); + us.Send (bb);//鍘熸牱杩斿洖缁欐湇鍔″櫒锛屾湇鍔″櫒鏄竴涓猠cho锛屼篃浼氬師鏍疯繑鍥 + } + /** + * + */ + public override void OnClose(USocket us,bool fromRemote) + { + Console.WriteLine ("杩炴帴琚叧闂細"+fromRemote); + } + public override void OnIdle(USocket us) + { + Console.WriteLine ("杩炴帴瓒呮椂锛"); + } + public override void OnOpen(USocket us) + { + Console.WriteLine ("杩炴帴寤虹珛"); + JsonData data = new JsonData (); + data ["cmd"] = 1; + data ["name"] = "浣犲ソ"; + data ["pwd"] = "ldfkjl"; + + Frame f = new Frame (512); + f.PutString (data.ToJson()); + f.End (); + us.Send (f); + } + public override void OnError(USocket us,string err) + { + Console.WriteLine ("閿欒锛"+err); + } + } +} + diff --git a/cocosocket4unity/cocosocket4unity/USocket.cs b/cocosocket4unity/cocosocket4unity/USocket.cs new file mode 100644 index 0000000..3fcbb66 --- /dev/null +++ b/cocosocket4unity/cocosocket4unity/USocket.cs @@ -0,0 +1,171 @@ +锘縰sing System; +using System.IO; +using System.Net; +using System.Net.Sockets; +using System.Threading; + +namespace cocosocket4unity +{ + public class USocket + { + private Socket clientSocket; + private SocketListner listner; + private Protocal protocal; + private string ip; + private int port; + private int status; + public static int STATUS_INIT=0; + public static int STATUS_CONNECTING=1; + public static int STATUS_CONNECTED=2; + public static int STATUS_CLOSED=3; + /** + * 鏋勯狅紙浣嗕笉瀹屽杽锛岄渶瑕佽缃洃鍚櫒鍜屽崗璁В鏋愬櫒F锛 + */ + public USocket() + { + } + /** + * 鏋勯 + */ + public USocket (SocketListner listner,Protocal protocal) + { + this.listner = listner; + this.protocal = protocal; + } + + /** + * 瑁呭叆涓涓洃鍚櫒F + */ + public void setLister (SocketListner listner) + { + this.listner = listner; + } + /** + * 瑁呭叆涓涓崗璁В鏋愬櫒 + */ + public void setProtocal(Protocal p) + { + this.protocal = p; + } + /** + * 杩炴帴鎸囧畾鍦板潃 + */ + public void Connect(string ip,int port) + { + this.status = STATUS_CONNECTING; + this.ip = ip; + this.port = port; + clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); + clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, true); + clientSocket.BeginConnect(this.ip, this.port, connected, this); + } + + /** + * 鍏抽棴杩炴帴 + */ + public void Close() + { + if(clientSocket != null && clientSocket.Connected) + { + clientSocket.Shutdown(SocketShutdown.Both); + clientSocket.Close(); + this.status = STATUS_CLOSED; + } + } + /** + * 杩炴帴鎴愬姛 + */ + private void connected(IAsyncResult asyncConnect) + { + if (this.clientSocket.Connected) + { + this.clientSocket.EndConnect(asyncConnect); + this.status = STATUS_CONNECTED; + this.listner.OnOpen (this); + Thread thread = new Thread(new ThreadStart(received)); + thread.IsBackground = true; + thread.Start(); + } + } + /** + *鍙戦 + */ + public IAsyncResult Send(Frame frame) + { + return this.Send (frame.GetData ()); + } + /** + *鍙戦 + */ + public IAsyncResult Send(ByteBuf buf) + { + try + { + byte[] msg=buf.GetRaw(); + IAsyncResult asyncSend = clientSocket.BeginSend (msg,buf.ReaderIndex(),buf.ReadableBytes(),SocketFlags.None,sended,buf); + return asyncSend; + } + catch + { + return null; + } + } + /** + * 鍙戦佹垚鍔熺殑鍥炶皟 + */ + private void sended (IAsyncResult ar) + { + ByteBuf bb = (ByteBuf)ar.AsyncState; + bb.ReaderIndex (bb.WriterIndex ()); + this.clientSocket.EndSend(ar); + } + /** + * 鎺ユ敹鏁版嵁 + */ + private void received() + { + ByteBuf buf=new ByteBuf(4096); + while (true) + { + if(!clientSocket.Connected) + { + this.status = STATUS_CLOSED; + this.listner.OnClose (this,true); + break; + } + try + { + int size = clientSocket.Receive(buf.GetRaw()); + if(size <= 0) + { + this.status = STATUS_CLOSED; + clientSocket.Close(); + this.listner.OnClose (this,true); + break; + } + buf.ReaderIndex(0); + buf.WriterIndex(size); + while (true) + { + ByteBuf frame = this.protocal.TranslateFrame(buf); + if (frame != null) + { + this.listner.OnMessage(this, frame); + } else + { + break; + } + } + } + catch (Exception e) + { + this.status = STATUS_CLOSED; + this.listner.OnError(this,e.Message); + break; + } + } + } + } +} + diff --git a/cocosocket4unity/cocosocket4unity/bin/Debug/cocosocket4unity.exe b/cocosocket4unity/cocosocket4unity/bin/Debug/cocosocket4unity.exe new file mode 100644 index 0000000..4bdd661 Binary files /dev/null and b/cocosocket4unity/cocosocket4unity/bin/Debug/cocosocket4unity.exe differ diff --git a/cocosocket4unity/cocosocket4unity/bin/Debug/cocosocket4unity.pdb b/cocosocket4unity/cocosocket4unity/bin/Debug/cocosocket4unity.pdb new file mode 100644 index 0000000..4fb5926 Binary files /dev/null and b/cocosocket4unity/cocosocket4unity/bin/Debug/cocosocket4unity.pdb differ diff --git a/cocosocket4unity/cocosocket4unity/bin/Debug/鏂板缓鏂囨湰鏂囨。.txt b/cocosocket4unity/cocosocket4unity/bin/Debug/鏂板缓鏂囨湰鏂囨。.txt new file mode 100644 index 0000000..e69de29 diff --git a/cocosocket4unity/cocosocket4unity/cocosocket4unity.csproj b/cocosocket4unity/cocosocket4unity/cocosocket4unity.csproj new file mode 100644 index 0000000..4d5557a --- /dev/null +++ b/cocosocket4unity/cocosocket4unity/cocosocket4unity.csproj @@ -0,0 +1,57 @@ + + + + Debug + x86 + 8.0.30703 + 2.0 + {E227176C-3062-40D0-AB28-74EC87FD818E} + Exe + cocosocket4unity + cocosocket4unity + v4.0 + + + True + full + False + bin\Debug + DEBUG; + prompt + 4 + x86 + True + + + none + True + bin\Release + prompt + 4 + x86 + True + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/cocosocket4unity/cocosocket4unity/obj/x86/Debug/cocosocket4unity.csproj.FileListAbsolute.txt b/cocosocket4unity/cocosocket4unity/obj/x86/Debug/cocosocket4unity.csproj.FileListAbsolute.txt new file mode 100644 index 0000000..ebf5659 --- /dev/null +++ b/cocosocket4unity/cocosocket4unity/obj/x86/Debug/cocosocket4unity.csproj.FileListAbsolute.txt @@ -0,0 +1,4 @@ +D:\projects\cocosocket4unity\cocosocket4unity\bin\Debug\cocosocket4unity.exe +D:\projects\cocosocket4unity\cocosocket4unity\bin\Debug\cocosocket4unity.pdb +D:\projects\cocosocket4unity\cocosocket4unity\obj\x86\Debug\cocosocket4unity.exe +D:\projects\cocosocket4unity\cocosocket4unity\obj\x86\Debug\cocosocket4unity.pdb diff --git a/cocosocket4unity/cocosocket4unity/obj/x86/Debug/cocosocket4unity.exe b/cocosocket4unity/cocosocket4unity/obj/x86/Debug/cocosocket4unity.exe new file mode 100644 index 0000000..4bdd661 Binary files /dev/null and b/cocosocket4unity/cocosocket4unity/obj/x86/Debug/cocosocket4unity.exe differ diff --git a/cocosocket4unity/cocosocket4unity/obj/x86/Debug/cocosocket4unity.pdb b/cocosocket4unity/cocosocket4unity/obj/x86/Debug/cocosocket4unity.pdb new file mode 100644 index 0000000..4fb5926 Binary files /dev/null and b/cocosocket4unity/cocosocket4unity/obj/x86/Debug/cocosocket4unity.pdb differ