轉自:http://www.unity3d8.com/content/c-socket串連伺服器代碼
using UnityEngine;using System.Collections;using System;using System.Threading;using System.Text;using System.Net;using System.Net.Sockets;public class SocketTest : MonoBehaviour{// Use this for initializationvoid Start(){int workerThreads, completionThreads;ThreadPool.GetAvailableThreads(out workerThreads, out completionThreads);Debug.Log("Worker: " + workerThreads + " Completion: " + completionThreads);Debug.Log("Setting IP address");IPAddress ipAddress = IPAddress.Parse("192.168.0.80");IPEndPoint ipEndpoint =new IPEndPoint(ipAddress, 8000);Debug.Log("Creating socket");Socket clientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);//Synchronous call//clientSocket.Connect(ipEndpoint);//byte[] sendBuffer = Encoding.ASCII.GetBytes("Hello");//clientSocket.Send(sendBuffer, 0, sendBuffer.Length, SocketFlags.None);//Console.Write("Connection in progress.");// StateObject stateObject =// new StateObject(16, clientSocket);//clientSocket.Receive(// stateObject.sBuffer,// 0,// stateObject.sBuffer.Length,// SocketFlags.None);//string message = Encoding.ASCII.GetString(stateObject.sBuffer);//Debug.Log(message);//clientSocket.Close();//Asynchronous callDebug.Log("Beginning Asynchronous call");IAsyncResult asyncConnect = clientSocket.BeginConnect(ipEndpoint,new AsyncCallback(connectCallback),clientSocket);Console.Write("Connection in progress.");if (writeDot(asyncConnect) == true){// allow time for callbacks to// finish before the program endsThread.Sleep(3000);}}// Update is called once per framevoid Update(){}// used to pass state information to delegateclass StateObject{internal byte[] sBuffer;internal Socket sSocket;internal StateObject(int size, Socket sock){sBuffer = new byte[size];sSocket = sock;}}public static void connectCallback(IAsyncResult asyncConnect){Debug.Log("Beginning connectCallback");Socket clientSocket =(Socket)asyncConnect.AsyncState;clientSocket.EndConnect(asyncConnect);Debug.Log("Operation Completed");// arriving here means the operation completed// (asyncConnect.IsCompleted = true) but not// necessarily successfullyif (clientSocket.Connected == false){Console.WriteLine(".client is not connected.");return;}else Console.WriteLine(".client is connected.");byte[] sendBuffer = Encoding.ASCII.GetBytes("Hello");IAsyncResult asyncSend = clientSocket.BeginSend(sendBuffer,0,sendBuffer.Length,SocketFlags.None,new AsyncCallback(sendCallback),clientSocket);Console.Write("Sending data.");writeDot(asyncSend);}public static void sendCallback(IAsyncResult asyncSend){Socket clientSocket = (Socket)asyncSend.AsyncState;int bytesSent = clientSocket.EndSend(asyncSend);Console.WriteLine(".{0} bytes sent.",bytesSent.ToString());StateObject stateObject =new StateObject(16, clientSocket);// this call passes the StateObject because it// needs to pass the buffer as well as the socketIAsyncResult asyncReceive =clientSocket.BeginReceive(stateObject.sBuffer,0,stateObject.sBuffer.Length,SocketFlags.None,new AsyncCallback(receiveCallback),stateObject);Console.Write("Receiving response.");writeDot(asyncReceive);}public static voidreceiveCallback(IAsyncResult asyncReceive){StateObject stateObject =(StateObject)asyncReceive.AsyncState;int bytesReceived =stateObject.sSocket.EndReceive(asyncReceive);string message = Encoding.ASCII.GetString(stateObject.sBuffer);Console.WriteLine(".{0} bytes received: {1}{2}{2}Shutting down.",bytesReceived.ToString(),message,Environment.NewLine);Debug.Log("bytes recieved " + bytesReceived + " Message: " + message);stateObject.sSocket.Shutdown(SocketShutdown.Both);stateObject.sSocket.Close();}// times out after 2 seconds but operation continuesinternal static bool writeDot(IAsyncResult ar){int i = 0;while (ar.IsCompleted == false){if (i++ > 20){Console.WriteLine("Timed out.");return false;}Console.Write(".");Thread.Sleep(100);}return true;}}