Unity3d 腳本與C#Socket服務器傳輸數據
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服務器傳輸數據