Files
plugin-library/Assets/00.StaryEvo/Runtime/UnitySocket/SocketClient/Scripts/SocketClientMain.cs

50 lines
1.3 KiB
C#
Raw Normal View History

2025-09-04 11:43:35 +08:00
using System.Text;
2025-07-02 10:05:26 +08:00
using UnityEngine;
public class SocketClientMain : MonoBehaviour
{
2025-09-04 11:43:35 +08:00
private SocketClient _client;
2025-07-02 10:05:26 +08:00
private string ip = "127.0.0.1";
private int port = 8080;
private void Awake()
{
_client = new SocketClient("192.168.31.67", 6854);
_client.Connect(() =>
{
2025-09-04 11:43:35 +08:00
Debug.Log("连接成功");
2025-07-02 10:05:26 +08:00
// _client.DisConnect();
2025-09-04 11:43:35 +08:00
}, () => { Debug.Log("连接失败"); });
2025-07-02 10:05:26 +08:00
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
2025-09-04 11:43:35 +08:00
var bytes = Encoding.UTF8.GetBytes("我是测试数据");
_client.Send((ushort)SocketEvent.ScTest, bytes);
2025-07-02 10:05:26 +08:00
}
2025-09-04 11:43:35 +08:00
if (Input.GetKeyDown(KeyCode.D)) _client.DisConnect();
2025-07-02 10:05:26 +08:00
}
private void OnDestroy()
{
// 注意由于Unity编译器环境下游戏开启/关闭只影响主线程的开关游戏关闭回调时需要通过Close函数来关闭服务端/客户端的线程。
2025-09-04 11:43:35 +08:00
if (_client != null) _client.Close();
}
public void StartConnect(string ip = "", int port = 0)
{
}
public void SendServer(SocketEvent socketEvent, string message)
{
var bytes = Encoding.UTF8.GetBytes(message);
_client.Send((ushort)socketEvent, bytes);
Debug.LogFormat("客户端发送数据 >>> {0}", message);
2025-07-02 10:05:26 +08:00
}
}