c# socket串連伺服器代碼

來源:互聯網
上載者:User

轉自: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;}}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.