c# socket连接服务器代码

转自: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 initialization

void 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 call

Debug.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 ends

Thread.Sleep(3000);

}

}



// Update is called once per frame

void Update()

{



}



// used to pass state information to delegate

class 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 successfully

if (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 socket

IAsyncResult asyncReceive =

clientSocket.BeginReceive(

stateObject.sBuffer,

0,

stateObject.sBuffer.Length,

SocketFlags.None,

new AsyncCallback(receiveCallback),

stateObject);



Console.Write("Receiving response.");

writeDot(asyncReceive);

}



public static void

receiveCallback(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 continues

internal 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;

}

}

你可能感兴趣的:(socket)