51 lines
1.2 KiB
C#
51 lines
1.2 KiB
C#
|
|
using System.Collections;
|
|||
|
|
using System.Collections.Generic;
|
|||
|
|
using UnityEngine;
|
|||
|
|
|
|||
|
|
public class SocketClientMain : MonoBehaviour
|
|||
|
|
{
|
|||
|
|
private string ip = "127.0.0.1";
|
|||
|
|
private int port = 8080;
|
|||
|
|
private SocketClient _client;
|
|||
|
|
|
|||
|
|
private void Awake()
|
|||
|
|
{
|
|||
|
|
_client = new SocketClient("192.168.31.67", 6854);
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
_client.Connect(() =>
|
|||
|
|
{
|
|||
|
|
UnityEngine.Debug.Log("连接成功");
|
|||
|
|
|
|||
|
|
// _client.DisConnect();
|
|||
|
|
}, () => { UnityEngine.Debug.Log("连接失败"); });
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public void StartConnect(string ip = "", int port = 0)
|
|||
|
|
{
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private void Update()
|
|||
|
|
{
|
|||
|
|
if (Input.GetKeyDown(KeyCode.A))
|
|||
|
|
{
|
|||
|
|
var bytes = System.Text.Encoding.UTF8.GetBytes("我是测试数据");
|
|||
|
|
_client.Send((System.UInt16)SocketEvent.ScTest, bytes);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if (Input.GetKeyDown(KeyCode.D))
|
|||
|
|
{
|
|||
|
|
_client.DisConnect();
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private void OnDestroy()
|
|||
|
|
{
|
|||
|
|
// 注意由于Unity编译器环境下,游戏开启/关闭只影响主线程的开关,游戏关闭回调时需要通过Close函数来关闭服务端/客户端的线程。
|
|||
|
|
if (_client != null)
|
|||
|
|
{
|
|||
|
|
_client.Close();
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|