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
}
}
`