http://www.unitymanual.com/home.php?mod=space&uid=287&do=blog&id=345
首先是服务器端代码,用法很简单,直接用VS新建一个控制台项目,把Program.cs里的代码全部替换就可以了。
[code]csharpcode:
001 | using System; |
002 | using System.Net; |
003 | using System.Net.Sockets; |
004 | using System.Reflection; |
005 | using System.Text; |
006 | using System.Threading; |
007 |
008 | namespace SaeaTest |
009 | { |
010 | class Program |
011 | { |
012 | static void Main( string [] args) |
013 | { |
014 | SocketServer ss = new SocketServer(); |
015 |
016 | ConsoleRun cr = new ConsoleRun(); |
017 | Thread tr = new Thread( new ThreadStart(cr.Run)); |
018 | tr.Start(); |
019 | } |
020 | } |
021 | public class SocketServer |
022 | { |
023 | private const string s_ip = "127.0.0.1" ; |
024 | private const int s_port = 9900; |
025 | public SocketServer() |
026 | { |
027 | IPAddress addr = IPAddress.Parse(s_ip); |
028 | new TcpListener().Listen( new IPEndPoint(addr, s_port)); |
029 | } |
030 | } |
031 |
032 | public class TcpListener |
033 | { |
034 | private SocketAsyncEventArgs Args; |
035 | private Socket ListenerSocket; |
036 | private StringBuilder buffers; |
037 |
038 | public void Listen(EndPoint e) |
039 | { |
040 | //buffer |
041 | buffers = new StringBuilder(); |
042 | //socket |
043 | ListenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); |
044 | ListenerSocket.Bind(e); |
045 | ListenerSocket.Listen(10); |
046 | //异步socket事件 |
047 | Args = new SocketAsyncEventArgs(); |
048 | Args.Completed += new EventHandler<SocketAsyncEventArgs>(ProcessAccept); |
049 | BeginAccept(Args); |
050 | Console.WriteLine( "server run at {0}" , e.ToString()); |
051 | } |
052 |
053 | //开始接受 |
054 | void BeginAccept(SocketAsyncEventArgs e) |
055 | { |
056 | e.AcceptSocket = null ; |
057 | if (!ListenerSocket.AcceptAsync(e)) |
058 | ProcessAccept(ListenerSocket, e); |
059 | } |
060 | //接受完毕 开始接收和发送 |
061 | void ProcessAccept( object sender, SocketAsyncEventArgs e) |
062 | { |
063 | Socket s = e.AcceptSocket; |
064 | e.AcceptSocket = null ; |
065 |
066 | int bufferSize = 10; //1000 * 1024; |
067 | var args = new SocketAsyncEventArgs(); |
068 | args.Completed += new EventHandler<SocketAsyncEventArgs>(OnIOCompleted); |
069 | args.SetBuffer( new byte [bufferSize], 0, bufferSize); |
070 | args.AcceptSocket = s; |
071 | if (!s.ReceiveAsync(args)) |
072 | ProcessReceive(args); |
073 |
074 | BeginAccept(e); |
075 | } |
076 |
077 | //IOCP回调 |
078 | void OnIOCompleted( object sender, SocketAsyncEventArgs e) |
079 | { |
080 | switch (e.LastOperation) |
081 | { |
082 | case SocketAsyncOperation.Receive: |
083 | ProcessReceive(e); |
084 | break ; |
085 | case SocketAsyncOperation.Send: |
086 | ProcessSend(e); |
087 | break ; |
088 | default : |
089 | throw new ArgumentException( "The last operation completed on the socket was not a receive or send" ); |
090 | } |
091 | } |
092 |
093 | public static string sSession = "" ; |
094 | //接收完毕 |
095 | void ProcessReceive(SocketAsyncEventArgs e) |
096 | { |
097 | if (e.BytesTransferred > 0) |
098 | { |
099 | if (e.SocketError == SocketError.Success) |
100 | { |
101 | //读取 |
102 | var data = Encoding.ASCII.GetString(e.Buffer, e.Offset, e.BytesTransferred); |
103 | buffers.Append(data); |
104 | Console.WriteLine( "Received:{0}" , data); //这是客户端发来的请求,在这里进行数据处理 |
105 |
106 | if (e.AcceptSocket.Available == 0) |
107 | { |
108 | //读取完毕 |
109 | //Console.WriteLine("Receive Complete.Data:{0}", buffers.ToString()); |
110 | //重置 |
111 | buffers = new StringBuilder(); |
112 | //发送反馈 |
113 | Byte[] sendBuffer = Encoding.ASCII.GetBytes( "result from server" ); |
114 | e.SetBuffer(sendBuffer, 0, sendBuffer.Length); |
115 | if (!e.AcceptSocket.SendAsync(e)) |
116 | { |
117 | ProcessSend(e); |
118 | } |
119 | } |
120 | else if (!e.AcceptSocket.ReceiveAsync(e)) |
121 | { |
122 | ProcessReceive(e); |
123 | } |
124 | } |
125 | } |
126 | } |
127 | //发送完毕 |
128 | void ProcessSend(SocketAsyncEventArgs e) |
129 | { |
130 | if (e.SocketError == SocketError.Success) |
131 | { |
132 |
133 | if (!e.AcceptSocket.ReceiveAsync(e)) |
134 | { |
135 | ProcessReceive(e); |
136 | } |
137 | } |
138 | } |
139 | } |
140 |
141 | class ConsoleRun |
142 | { |
143 | public void Run() |
144 | { |
145 | while ( true ) |
146 | { |
147 | string scmd = Console.ReadLine(); |
148 | string [] acmds = scmd.Split( ' ' ); |
149 | if (acmds[0] == "session" && acmds.Length == 2) |
150 | { |
151 | TcpListener.sSession = acmds[1]; |
152 | Console.WriteLine( "cur session is " + TcpListener.sSession); |
153 | } |
154 | } |
155 | } |
156 | } |
157 | } |
客户端代码很简单,大家可以把下面的代码直接保存成cs,然后在自己的Unity项目里直接new一个SAEAClient类出来就可以send了。
[code]csharpcode:
01 | public class <span style= "font-family: Tahoma, Arial, Helvetica, snas-serif; font-size: 14px; white-space: normal;" >SAEAClient</span> |
02 | { |
03 | private const string s_ip = "<span style=" font-size: 9pt; line-height: 1.8em; ">127.0.0.1</span><span style=" font-size: 9pt; line-height: 1.8em; ">" ;</span><br> private const int s_port = 9900; |
04 | public SAEAClient() |
05 | { |
06 | ConnectToServer(); |
07 | } |
08 |
09 | public bool connected |
10 | { |
11 | get { return socket != null ; } |
12 | } |
13 |
14 | private Socket socket; |
15 | private void ConnectToServer() |
16 | { |
17 | IPAddress ip = IPAddress.Parse(s_ip); |
18 | socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); |
19 | try |
20 | { |
21 | socket.Connect(s_ip, s_port); |
22 | } |
23 | catch |
24 | { |
25 | Console.WriteLine( "connect failed" ); |
26 | } |
27 | } |
28 |
29 | public void Send( string spkt) |
30 | { |
31 | if (socket == null ) |
32 | { |
33 | return ; |
34 | } |
35 | socket.Send(Encoding.ASCII.GetBytes(spkt)); |
36 | } |
37 | } |