tcp局域网简单通讯

using UnityEngine;

using System;

using System.Net;

using System.Net.Sockets;

using System.Text;

using System.Threading;

///using PimDeWitte.UnityMainThreadDispatcher;

using UnityEngine.UI;

using UnityEngine.Video;

using System.IO;

using System.Collections;

using UnityEngine.Networking;

using System.Collections.Generic;

using System.Linq;

public class TCPServer : MonoBehaviour

{

// Port to listen for incoming connections

public int serverPort = 8888;

// TCP listener
TcpListener listener;

//public Test Test;

// Start is called before the first frame update
void Start()
{

// Test = GetComponent();

StartServer();

// PlayVideo("初始场景");

}

// Method to start the TCP server
void StartServer()
{
    try
    {
        listener = new TcpListener(IPAddress.Any, serverPort);
        listener.Start();
        Debug.Log("Server started, listening on port " + serverPort);
        isCliect = true;

        // Start accepting incoming connections in a separate thread
        Thread acceptThread = new Thread(new ThreadStart(AcceptConnections));
        acceptThread.Start();
    }
    catch (Exception e)
    {
      //  Debug.LogError("Failed to start server: " + e.Message);
    }
}

// Method to accept incoming connections
void AcceptConnections()
{
    while (true)
    {
        try
        {
            TcpClient client = listener.AcceptTcpClient();
            Debug.Log("Client connected: " + ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString());

            // Handle client communication in a separate thread
            Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClient));
            clientThread.Start(client);
        }
        catch (Exception e)
        {
            //Debug.LogError("Error accepting client connection: " + e.Message);
        }
    }
}

// Method to handle client communication
List<byte> buffer = new List<byte>();
void HandleClient(object clientObj)
{

    TcpClient client = (TcpClient)clientObj;
    NetworkStream stream = client.GetStream();

    byte[] tempBuffer = new byte[1024];
  //  int bytesRead;
    
    while (isCliect)
    {
        try
        {
            int bytesRead = stream.Read(tempBuffer, 0, tempBuffer.Length);
            buffer.AddRange(tempBuffer.Take(bytesRead));
            if (buffer.Contains((byte)'\n'))
            {
                byte[] completeData = buffer.ToArray();
                string message = Encoding.UTF8.GetString(completeData, 0, completeData.Length - 1); // 移除分隔符
                buffer.Clear(); // 清空缓冲区
                if (string.IsNullOrEmpty(message)) AcceptConnections();
                else
                {
                    Debug.LogError(message);
                    StreamingAssetsEnumerator.instances.play(message);
                }
                Debug.Log(message);       // 处理数据...
            }
            // Read data from the client
           
                

            // 在这里处理接收到的消息并发送响应消息给客户端
            // Perform action based on received data


          

            
        }
        catch (Exception e)
        {
            Debug.LogError("Error receiving data from client: " + e.Message);
        }
    }

    client.Close();
}

public bool isCliect = false;
// Method to stop the server
void OnApplicationQuit()
{
    if (listener != null)
    {
        listener.Stop();
        isCliect = false;
    }
}

}

服务器端从streamingassets下读取图片或者视频需要插入插件UnityMainThreadDispatcher-master插件

using UnityEngine;

using System;

using System.Net;

using System.Net.Sockets;

using System.Text;

using System.Threading;

using UnityEngine.UI;

public class TCPClient : MonoBehaviour

{

// IP address and port of the server

public string serverIP; // Replace with the IP address of your computer

public int serverPort;

// TCP client
TcpClient client;
NetworkStream stream;

public Image signal;



public Button Quit;
// Start is called before the first frame update
void Start()
{
    Quit.onClick.AddListener(() => QuitApp());

    serverIP = IPReader.ipAddress;
    serverPort = IPReader.port;
    ConnectToServer();
    //ContentServer();
    // InvokeRepeating("Reconnect", 1f, 1f);
}

// Method to connect to the server



void ContentServer()
{
    try
    {
        client = new TcpClient(serverIP, serverPort);
        Debug.Log("连接成功!");
        stream = client.GetStream();
        signal.color = Color.green;
        // 这里可以添加已连接的处理逻辑
    }
    catch (SocketException)
    {
        Debug.Log("连接失败!");
        signal.color = Color.red;
        // 处理连接失败的情况
    }

}





void ConnectToServer()
{

    while (true)
    {
        try
        {
            client = new TcpClient();
            client.Connect(serverIP, serverPort);
            stream = client.GetStream();
            Debug.Log("Connected to server.");

            signal.color = Color.green;
            // Start listening for incoming messages in a separate thread
            Thread receiveThread = new Thread(new ThreadStart(ReceiveData));
            receiveThread.Start();
            break; // Exit the loop once connected
        }
        catch (Exception e)
        {
            break;
            Debug.LogError("Failed to connect to server: " + e.Message);
            signal.color = Color.red;

            Thread.Sleep(3000); // Wait for 3 seconds before attempting to reconnect
        }
    }
}

// Method to receive data from the server
void ReceiveData()
{
    byte[] buffer = new byte[1024];
    int bytesRead;

    while (true)
    {
        try
        {
            // Read data from the server
            bytesRead = stream.Read(buffer, 0, buffer.Length);
            string receivedData = Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Debug.LogError("Received data from server: " + receivedData);
        }
        catch (Exception e)
        {
            Debug.LogError("Error receiving data from server: " + e.Message);
            break;
        }
    }
}


// Method to send data to the server
public void SendData(byte[] data)
{

    if (stream == null || !client.Connected) ConnectToServer();
    if (stream != null && client.Connected)
    {
        byte[] sendData = data;
        stream.Write(sendData, 0, sendData.Length);
        Debug.Log("Sent data to server: " + data);
    }
}

// Clean up resources when the application quits
void OnApplicationQuit()
{
    if (client != null && client.Connected)
    {
        client.Close();
    }
}


public void QuitApp()
{

#if UNITY_EDITOR

UnityEditor.EditorApplication.isPlaying = false;

#else

Application.Quit();

#endif

}

}

`

相关推荐
青春:一叶知秋10 小时前
【Linux网络编程】数据链路层
运维·服务器·网络
不悔哥10 小时前
使用openwrt搭建ipsec隧道
linux·c语言·网络·tcp/ip·智能路由器·openwrt
爱吃喵的鲤鱼10 小时前
Linux——网络基础(1)
linux·运维·网络
山禾女鬼00112 小时前
深入了解 HTTP 头部中的 Accept-Encoding:gzip、deflate、br、zstd
网络·网络协议·http
Andya_net12 小时前
网络安全 | F5-Attack Signatures详解
网络·安全·web安全
HMS工业网络13 小时前
通过OPC UA或MQTT协议,安全地将工业设备连接至物联网软件
网络·物联网·安全
Themberfue14 小时前
Java 网络原理 ②-IP协议
网络·网络协议·计算机网络·ip·ipv4·网络层·ip协议
路由侠内网穿透14 小时前
无公网IP 外网访问本地部署 llamafile 大语言模型
网络协议·tcp/ip·语言模型
比扬云15 小时前
SD-WAN站点和客户端的区别
网络·c++·云计算·边缘计算·sd-wan·sase
Kacey Huang16 小时前
长短期记忆网络LSTM
网络·rnn·数学建模·lstm