Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add client for socket communications #402

Merged
merged 1 commit into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions Scripts/Network/SocketClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
using System;
using System.Net.Sockets;
using System.Text;
using UnityEngine;

namespace ChatdollKit.Network
{
public class SocketClient : MonoBehaviour
{
private TcpClient client;
private NetworkStream stream;
[SerializeField]
private string address = "127.0.0.1";
public string Address { get { return address; } }
[SerializeField]
private int port = 0;
public int Port { get { return port; } }

public bool IsConnected { get { return client != null && client.Connected; }}

public void Connect(string address = null, int port = 0)
{
if (!string.IsNullOrEmpty(address))
{
this.address = address;
}

if (port > 0)
{
this.port = port;
}

try
{
client = new TcpClient(Address, Port);
stream = client.GetStream();
Debug.Log($"Connected to server: {Address}:{Port}");
}
catch (Exception ex)
{
Debug.LogError($"Failed to connect to server: {ex.Message}");
}
}

public void SendMessageToServer(string message)
{
if (client == null || !client.Connected)
{
Debug.LogError("Not connected to the server.");
return;
}

try
{
byte[] data = Encoding.UTF8.GetBytes(message + "\n");
stream.Write(data, 0, data.Length);
}
catch (Exception ex)
{
Debug.LogError($"Failed to send message: {ex.Message}");
}
}

void OnApplicationQuit()
{
Disconnect();
}

public void Disconnect()
{
if (stream != null) stream.Close();
if (client != null) client.Close();
Debug.Log("Disconnected from server.");
}
}
}
11 changes: 11 additions & 0 deletions Scripts/Network/SocketClient.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.