標籤:family res type write intern amp round ons name
Test.cs指令碼
---------------------------------------------------------------------------------------------------------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using AssemblyCSharp;
using System.Text;
using System;
using System.Threading;
public class Test : MonoBehaviour {
private JFSocket mJFSocket;
// Use this for initialization
void Start () {
mJFSocket = JFSocket.GetInstance();
}
// Update is called once per frame
void Update () {
if(mJFSocket!=null){
Debug.Log (mJFSocket.receive_msg);
}
}
}
---------------------------------------------------------------------------------------------------------------------------------------------------
SocketClientTest.cs
---------------------------------------------------------------------------------------------------------------------------------------------------
using UnityEngine;
using System.Collections;
using System;
using System.Threading;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace AssemblyCSharp
{
public class SocketClientTest
{
//Socket用戶端對象
private Socket clientSocket;
//單例模式
private static SocketClientTest instance;
public string receive_msg = "";
public static SocketClientTest GetInstance()
{
if (instance == null)
{
instance = new SocketClientTest();
}
return instance;
}
//單例的建構函式
SocketClientTest()
{
//建立Socket對象, 這裡我的連線類型是TCP
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//伺服器IP地址
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
//伺服器連接埠
IPEndPoint ipEndpoint = new IPEndPoint(ipAddress, 5209);
//這是一個非同步建立串連,當串連建立成功時調用connectCallback方法
IAsyncResult result = clientSocket.BeginConnect(ipEndpoint, new AsyncCallback(connectCallback), clientSocket);
//這裡做一個逾時的監測,當串連超過5秒還沒成功表示逾時
bool success = result.AsyncWaitHandle.WaitOne(5000, true);
if (!success)
{
//逾時
Closed();
Debug.Log("connect Time Out");
}
else
{
//Debug.Log ("與socket建立串連成功,開啟線程接受服務端資料");
//與socket建立串連成功,開啟線程接受服務端資料。
Thread thread = new Thread(new ThreadStart(ReceiveSorketMsg));
thread.IsBackground = true;
thread.Start();
}
}
private void connectCallback(IAsyncResult asyncConnect)
{
Debug.Log("connectSuccess");
}
private void ReceiveSorketMsg()
{
Console.WriteLine ("wait---");
//在這個線程中接受伺服器返回的資料
while (true)
{
if (!clientSocket.Connected)
{
//與伺服器中斷連線跳出迴圈
Debug.Log("Failed to clientSocket server.");
clientSocket.Close();
break;
}
try
{
//接受資料儲存至bytes當中
byte[] bytes = new byte[4096];
//Receive方法中會一直等待服務端回傳訊息
//如果沒有回傳會一直在這裡等著。
int i = clientSocket.Receive(bytes);
if (i <= 0)
{
clientSocket.Close();
break;
}
Debug.Log(Encoding.ASCII.GetString(bytes, 0, i));
if (bytes.Length > 8)
{
//Console.WriteLine("接收伺服器訊息:{0}", Encoding.ASCII.GetString(bytes, 0, i));
receive_msg = Encoding.ASCII.GetString(bytes, 0, i);
}
else
{
Debug.Log("length is not > 8");
}
}
catch (Exception e)
{
Debug.Log("Failed to clientSocket error." + e);
clientSocket.Close();
break;
}
}
}
//關閉Socket
public void Closed()
{
if (clientSocket != null && clientSocket.Connected)
{
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
clientSocket = null;
}
}
}
---------------------------------------------------------------------------------------------------------------------------------------------------
Socket服務端代碼:
using System;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace SocketServerTest01
{
class Program
{
private static byte[] result = new byte[1024];
private static int myProt = 5209; //連接埠
static Socket serverSocket;
static void Main(string[] args)
{
//伺服器IP地址
IPAddress ip = IPAddress.Parse("127.0.0.1");
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(ip, myProt)); //綁定IP地址:連接埠
serverSocket.Listen(10); //設定最多10個排隊串連請求
Console.WriteLine("啟動監聽{0}成功", serverSocket.LocalEndPoint.ToString());
//通過Clientsoket發送資料
Socket clientSocket = serverSocket.Accept();
while (true) {
Thread.Sleep(1000);
SendMsg(clientSocket);
}
}
/// <summary>
/// 以每秒一次的頻率發送資料給用戶端
/// </summary>
/// <param name="clientSocket"></param>
public static void SendMsg(Socket clientSocket)
{
try
{
clientSocket.Send(Encoding.ASCII.GetBytes(GetRandomData()));
}
catch {
Console.WriteLine("伺服器異常");
return;
}
}
/// <summary>
/// 產生隨機字串
/// </summary>
/// <returns></returns>
private static string GetRandomData()
{
Random ran = new Random();
int x = ran.Next(50,200);
int y = ran.Next(20,100);
int z = 1000;
int ID = ran.Next(1,30);
string str = "ID:"+ID+"-x:"+x+"-y:"+y+"-z:"+z;
return str;
}
}
}
Unity3d 指令碼與C#Socket伺服器傳輸資料