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

复制代码
}

}

`

相关推荐
可乐加.糖15 小时前
一篇关于Netty相关的梳理总结
java·后端·网络协议·netty·信息与通信
大丈夫立于天地间15 小时前
ISIS协议中的数据库同步
运维·网络·信息与通信
Dream Algorithm15 小时前
路由器的 WAN(广域网)口 和 LAN(局域网)口
网络·智能路由器
IT猿手15 小时前
基于CNN-LSTM的深度Q网络(Deep Q-Network,DQN)求解移动机器人路径规划,MATLAB代码
网络·cnn·lstm
吴盐煮_15 小时前
使用UDP建立连接,会存在什么问题?
网络·网络协议·udp
hyshhhh16 小时前
【算法岗面试题】深度学习中如何防止过拟合?
网络·人工智能·深度学习·神经网络·算法·计算机视觉
Hellc00716 小时前
轮询、WebSocket 和 SSE:实时通信技术全面指南(含C#实现)
网络
xujiangyan_17 小时前
nginx的反向代理和负载均衡
服务器·网络·nginx
GalaxyPokemon17 小时前
Muduo网络库实现 [十] - EventLoopThreadPool模块
linux·服务器·网络·c++